Immune dysregulation has been widely observed in patients with psychiatric disorders. This study aims to examine the association between HLA alleles and depression and anxiety. Using data from the UK Biobank, we performed regression analyses to assess the association of 359 HLA alleles with depression and anxiety, as determined by Patient Health Questionnaire (PHQ) score (n = 120,033), self‐reported depression (n = 121,685), general anxiety disorder (GAD‐7) score (n = 120,590), and self‐reported anxiety (n = 108,310). Subsequently, we conducted gene environmental interaction study (GEIS) to evaluate the potential effects of interactions between HLA alleles and environmental factors on the risk of depression and anxiety. Sex stratification was implemented in all analysis. Our study identified two significant HLA alleles associated with self‐reported depression, including HLA‐C*07:01 (β = −0.015, p = 5.54 × 10−5) and HLA‐B*08:01 (β = −0.015, p = 7.78 × 10−5). Additionally, we identified four significant HLA alleles associated with anxiety score, such as HLA‐DRB1*07:01 (β = 0.084, p = 9.28 × 10−5) and HLA‐B*57:01 (β = 0.139, p = 1.22 × 10−4). GEIS revealed that certain HLA alleles interacted with environmental factors to influence mental health outcomes. For instance, HLA‐A*02:07 × cigarette smoking was associated with depression score (β = 0.976, p = 1.88 × 10−6). Moreover, sex stratification analysis revealed significant sex‐based differences in the interaction effects of certain HLA alleles with environmental factors. Our findings indicate the considerable impact of HLA alleles on the risks of depression and anxiety, providing valuable insights into the functional relevance of immune dysfunction in these conditions.