Animals adaptively respond to a tactile stimulus by choosing an ethologically relevant behavior depending on the location of the stimuli. Here, we investigate how somatosensory inputs on different body segments are linked to distinct motor outputs in Drosophila larvae. Larvae escape by backward locomotion when touched on the head, while they crawl forward when touched on the tail. We identify a class of segmentally repeated second-order somatosensory interneurons, that we named Wave, whose activation in anterior and posterior segments elicit backward and forward locomotion, respectively. Anterior and posterior Wave neurons extend their dendrites in opposite directions to receive somatosensory inputs from the head and tail, respectively. Downstream of anterior Wave neurons, we identify premotor circuits including the neuron A03a5, which together with Wave, is necessary for the backward locomotion touch response. Thus, Wave neurons match their receptive field to appropriate motor programs by participating in different circuits in different segments.