Longevity is modulated by a range of conserved genes in eukaryotes, but it is unclear how variation in these genes contributes to the evolution of longevity in nature. Mutations that increase life span in model organisms typically induce trade-offs which lead to a net reduction in fitness, suggesting that such mutations are unlikely to become established in natural populations. However, the fitness consequences of manipulating longevity have rarely been assessed in heterogeneous environments, in which stressful conditions are encountered. Using laboratory selection experiments, we demonstrate that long-lived, stress-resistant Caenorhabditis elegans age-1(hx546) mutants have higher fitness than the wild-type genotype if mixed genotype populations are periodically exposed to high temperatures when food is not limited. We further establish, using stochastic population projection models, that the age-1(hx546) mutant allele can confer a selective advantage if temperature stress is encountered when food availability also varies over time. Our results indicate that heterogeneity in environmental stress may lead to altered allele frequencies over ecological timescales and indirectly drive the evolution of longevity. This has important implications for understanding the evolution of life-history strategies.