Iron needs both oxygen and water to rust. So rusting can be prevented by keeping one of them away from the iron, or by using a more reactive metal to protect it.
To exclude oxygen, an iron object can be coated with paint, oil, grease or plastic, which forms a barrier, or it can be stored in nitrogen. To exclude water, the object can be kept dry, for example by packing it with a drying agent such as calcium chloride. A coating of paint, oil or grease excludes both oxygen and water at once.
Sacrificial protection uses a more reactive metal such as zinc or magnesium in contact with the iron. The more reactive metal loses electrons and is oxidised in preference to the iron, so it corrodes instead and the iron is protected. Blocks of magnesium are bolted to steel ship hulls and buried pipes, and are replaced once they have corroded away. Galvanised iron is coated in zinc. The zinc acts as a barrier, and if it is scratched the zinc still corrodes first, so the iron underneath does not rust.