Spatial variation in pathogen-mediated selection is predicted to influence the evolutionary trajectory of host populations and lead to spatial variation in their immunogenetic composition. However, to date few studies have been able to directly link small-scale spatial variation in infection risk to host immune gene evolution in natural, nonhuman populations. Here, we use a natural rodent-Borrelia system to test for associations between landscape-level spatial variation in Borrelia infection risk along replicated elevational gradients in the Swiss Alps and Toll-like receptor 2 (TLR2) evolution, a candidate gene for Borrelia resistance, across bank vole (Myodes glareolus) populations. We found that Borrelia infection risk (i.e., the product of Borrelia prevalence in questing ticks and the average tick load of voles at a sampling site) was spatially variable and significantly negatively associated with elevation. Across sampling sites, Borrelia prevalence in bank voles was significantly positively associated with Borrelia infection risk along the elevational clines. We observed a significant association between naturally occurring TLR2 polymorphisms in hosts and their Borrelia infection status. The TLR2 variant associated with a reduced likelihood of Borrelia infection was most common in rodent populations at lower elevations that face a high Borrelia infection risk, and its frequency changed in accordance with the change in Borrelia infection risk along the elevational clines. These results suggest that small-scale spatial variation in parasite-mediated selection affects the immunogenetic composition of natural host populations, providing a striking example that the microbial environment shapes the evolution of the host's immune system in the wild. © 2018 John Wiley & Sons Ltd.