Mechanisms that control aging are important yet poorly defined. To discover longevity control genes, we performed a forward genetic screen for delayed reproductive aging in C. elegans. Here, we show that am117 is a nonsense mutation in the phm-2 gene, which encodes a protein homologous to human scaffold attachment factor B. phm-2(lf) mutant worms have an abnormal pharynx grinder, which allows live bacteria to accumulate in the intestine. This defect shortens lifespan on highly pathogenic bacteria but extends lifespan and health span on the standard E. coli diet by activating innate immunity pathways that lead to bacterial avoidance behavior and dietary restriction. eat-2(lf) mutants displayed a similar phenotype, indicating accumulation of live bacteria also triggers extended longevity in this mutant. The analysis of phm-2 elucidates connections between pathogen response and aging by defining a mechanism of longevity extension in C. elegans-bacterial colonization, innate immune activation, and bacterial avoidance behavior.