Consumption of unhealthy diets is exacerbating the burden of age-related ill health in aging populations. Such diets can program mammalian physiology to cause long-term, detrimental effects. Here, we show that, in Drosophila melanogaster, an unhealthy, high-sugar diet in early adulthood programs lifespan to curtail later-life survival despite subsequent dietary improvement. Excess dietary sugar promotes insulin-like signaling, inhibits dFOXO-the Drosophila homolog of forkhead box O (FOXO) transcription factors-and represses expression of dFOXO target genes encoding epigenetic regulators. Crucially, dfoxo is required both for transcriptional changes that mark the fly's dietary history and for nutritional programming of lifespan by excess dietary sugar, and this mechanism is conserved in Caenorhabditis elegans. Our study implicates FOXO factors, the evolutionarily conserved determinants of animal longevity, in the mechanisms of nutritional programming of animal lifespan.