Microbial pathogens impose selective pressures on their hosts, and combatting these pathogens is fundamental to the propagation of a species. Innate immunity is an ancient system that provides the foundation for pathogen resistance, with epithelial cells in humans increasingly appreciated to play key roles in innate defense. Here, we show that the nematode C. elegans displays genetic variation in epithelial immunity against intestinal infection by its natural pathogen, Nematocida parisii. This pathogen belongs to the microsporidia phylum, which comprises a large phylum of over 1400 species of fungal-related parasites that can infect all animals, including humans, but are poorly understood. Strikingly, we find that a wild C. elegans strain from Hawaii is able to clear intracellular infection by N. parisii, with this ability restricted to young larval animals. Notably, infection of older larvae does not impair progeny production, while infection of younger larvae does. The early-life immunity of Hawaiian larvae enables them to produce more progeny later in life, providing a selective advantage in a laboratory setting--in the presence of parasite it is able to out-compete a susceptible strain in just a few generations. We show that enhanced immunity is dominant to susceptibility, and we use quantitative trait locus mapping to identify four genomic loci associated with resistance. Furthermore, we generate near-isogenic strains to directly demonstrate that two of these loci influence resistance. Thus, our findings show that early-life immunity of C. elegans against microsporidia is a complex trait that enables the host to produce more progeny later in life, likely improving its evolutionary success.