When flying or swimming, animals must adjust their own movement to compensate for displacements induced by the flow of the surrounding air or water. These flow-induced displacements can most easily be detected as visual whole-field motion with respect to the animal's frame of reference. Despite this, many aquatic animals consistently orient and swim against oncoming flows (a behaviour known as rheotaxis) even in the absence of visual cues. How animals achieve this task, and its underlying sensory basis, is still unknown. Here we show that, in the absence of visual information, larval zebrafish (Danio rerio) perform rheotaxis by using flow velocity gradients as navigational cues. We present behavioural data that support a novel algorithm based on such local velocity gradients that fish use to avoid getting dragged by flowing water. Specifically, we show that fish use their mechanosensory lateral line to first sense the curl (or vorticity) of the local velocity vector field to detect the presence of flow and, second, to measure its temporal change after swim bouts to deduce flow direction. These results reveal an elegant navigational strategy based on the sensing of flow velocity gradients and provide a comprehensive behavioural algorithm, also applicable for robotic design, that generalizes to a wide range of animal behaviours in moving fluids.