Every host is colonized by a variety of microbes, some of which can protect their hosts from pathogen infection. However, pathogen presence naturally varies over time in nature, such as in the case of seasonal epidemics. We experimentally coevolved populations of Caenorhabditis elegans worm hosts with bacteria possessing protective traits (Enterococcus faecalis), in treatments varying the infection frequency with pathogenic Staphylococcus aureus every host generation, alternating host generations, every fifth host generation or never. We additionally investigated the effect of initial pathogen presence at the formation of the defensive symbiosis. Our results show that enhanced microbe-mediated protection evolved during host-protective microbe coevolution when faced with rare infections by a pathogen. Initial pathogen presence had no effect on the evolutionary outcome of microbe-mediated protection. We also found that protection was only effective at preventing mortality during the time of pathogen infection. Overall, our results suggest that resident microbes can be a form of transgenerational immunity against rare pathogen infection.