The association between type 2 diabetes mellitus (T2DM), lifestyle factors, and the risk of osteoporosis (OP) is well-established. However, the impact of a healthy lifestyle on diabetes-related osteoporosis needs further investigation. Our objective was to explore if a combination of healthy lifestyle factors could mitigate the risk of OP in individuals with type 2 diabetes. This longitudinal analysis included 237,725 middle-aged and older participants. An overall lifestyle score, ranging from 0 to 7, was calculated by assigning a point for each of the seven healthy lifestyle factors, including no current smoking, non-excessive alcohol consumption, regular physical activity, healthy diet, adequate sleep duration, less sedentary behavior, and adequate sunshine exposure. During a median follow-up 12.21 years, 5760 OP cases were documented. Participants with T2DM showed a higher risk of OP than those without diabetes. Compared with participants without diabetes who had a lifestyle score of 6-7, the hazard ratios (HRs) for OP were 1.58 (95% CI 1.23-2.03), 1.62 (95% CI 1.16-2.25), and 2.58 (95% CI 1.64-4.05) for participants with T2DM who had a lifestyle score of 4, 3, and 0-2, respectively. There was a graded association between higher lifestyle scores and lower risks of incident OP among participants without diabetes as well as among those with T2DM. We estimated that the population attributable fraction for not adhering to 6-7 lifestyle behaviors was 15.7%. Participants with T2DM who adhered to a variety of healthy lifestyle factors demonstrated a substantially reduced risk of developing OP.