Objectives The global prevalence of diabetes is continuously rising, and the gut microbiota is closely associated with it. The Dietary Index for Gut Microbiota (DI-GM) assesses the impact of diet on the microbiota, but its association with diabetes risk remains unclear. This study aims to investigate the association between DI-GM and the risk of diabetes and analyze the mediating roles of phenotypic age and body mass index (BMI). Methods Utilizing data from the National Health and nutrition examination survey (NHANES) 1999-2018, we included 17,444 adults aged 20 years and older. DI-GM (score range: 0-13) was calculated based on dietary recall. Diabetes was diagnosed based on laboratory results and self-reported information. Multivariable logistic regression was used to analyze the association between DI-GM and diabetes, adjusting for relevant covariates. Mediation analysis evaluated the roles of phenotypic age and BMI. Results After adjusting for confounders, higher DI-GM scores were significantly associated with a lower risk of diabetes (OR = 0.93, 95% CI = 0.90-0.96, p < 0.001). Compared to the group with DI-GM scores of 0-3, those with scores of 5 (OR = 0.76, 95% CI = 0.67-0.86) and >= 6 (OR = 0.77, 95% CI = 0.68-0.88) had significantly reduced diabetes risk. Phenotypic age and BMI accounted for 41.02 and 25.57% of the association between DI-GM and diabetes, respectively. Conclusion Higher DI-GM scores are associated with a lower risk of diabetes, partially mediated through reduced phenotypic age and BMI.