Objective We aimed to study (1) to what extent the influence of low sun exposure on multiple sclerosis (MS) risk is mediated by low vitamin D levels; (2) whether low sun exposure or vitamin D deficiency act synergistically with HLA-DRB1*15:01 and absence of HLA-A*02:01. Methods We used two population-based case-control studies (7069 cases, 6632 matched controls). Subjects with different HLA alleles, sun exposure habits and vitamin D status were compared regarding MS risk, by calculating odds ratios (OR) with 95% confidence intervals (CI) employing logistic regression. Mediation analysis was used to identify the potential mediation effect of vitamin D on the relationship between low sun exposure and MS risk. Results Low sun exposure increased MS risk directly as well as indirectly, by affecting vitamin D status. The direct effect, expressed as OR, was 1.26 (95% CI 1.04-1.45) and the indirect effect, mediated by vitamin D deficiency, was 1.10 (95% CI 1.02-1.23). Of the total effect, nearly 30% was mediated by vitamin D deficiency. There was a significant interaction between low sun exposure and vitamin D deficiency (attributable proportion due to interaction 0.3, 95% CI 0.04-0.5) accounting for about 12% of the total effect. Further, both factors interacted with HLA-DRB1*15:01 to increase MS risk. Interpretation Our findings indicate that low sun exposure acts both directly on MS risk as well as indirectly, by leading to low vitamin D levels. The protective effect of sun exposure thus seems to involve both vitamin D and non-vitamin D pathways, which is of relevance for prevention, in particular for those with a genetic susceptibility to MS.