Hydrogen peroxide (H2O2) is the most common chemical threat that organisms face. Here, we show that H2O2 alters the bacterial food preference of Caenorhabditis elegans, enabling the nematodes to find a safe environment with food. H2O2 induces the nematodes to leave food patches of laboratory and microbiome bacteria when those bacterial communities have insufficient H2O2-degrading capacity. The nematode’s behavior is directed by H2O2-sensing neurons that promote escape from H2O2 and by bacteria-sensing neurons that promote attraction to bacteria. However, the input for H2O2-sensing neurons is removed by bacterial H2O2-degrading enzymes and the bacteria-sensing neurons’ perception of bacteria is prevented by H2O2. The resulting cross-attenuation provides a general mechanism that ensures the nematode’s behavior is faithful to the lethal threat of hydrogen peroxide, increasing the nematode’s chances of finding a niche that provides both food and protection from hydrogen peroxide.