Bacterial motility is typically studied in bulk solution, while their natural habitats often are complex environments. Here, we produced microfluidic channels that contained sediment-mimicking obstacles to study swimming of magnetotactic bacteria in a near-realistic environment that resembles their natural habitat. Magnetotactic bacteria are microorganisms that form chains of nanomagnets and that orient in the Earth magnetic field. The obstacles were produced based on micro-computer tomography reconstructions of bacteria-rich sediment samples. We characterized the swimming of magnetotactic bacteria through these channels and found that swimming throughput was highest for physiological magnetic fields. This observation was confirmed by extensive computer simulations using an active Brownian particle model, which were parameterized based on experimental trajectories, in particular with the trajectories near the sedimentmimicking obstacles, from which the interactions of the swimming bacteria with the obstacles were determined. The simulations were used to quantify the swimming throughput in detail. They showed the behavior seen in experiments, but also exhibited considerable variability between different channel geometries. The simulations indicate that swimming at strong field is impeded by the trapping of bacteria in “corners” that require transient swimming against the magnetic field for escape. At weak fields, the direction of swimming is almost random, making the process inefficient as well. We confirmed the trapping effect in our experiments and showed that lowering the field strength allows the bacteria to escape. We hypothesize that over the course of evolution, magnetotactic bacteria have thus evolved to produce magnetic properties that are adapted to the geomagnetic field in order to balance movement and orientation in such crowded environments.