How do hematite and magnetite form?
In nature, iron can be either metallic ($\ce{Fe^0}$), ferrous ($\ce{Fe^2+}$) or ferric ($\ce{Fe^3+}$).

In hematite, all of the iron is ferric: $\ce{Fe^3+_2O3}$. In magnetite, it is a combination of both ferric and ferrous: $\ce{Fe^2+Fe^3+_2O4}$. Thus, whether it is magnetite or hematite that are stable is mostly determined by the oxidation state of iron.

Let's look at an Eh-pH diagram:



This $x$ axis is the pH - the acidity of the system. Low pH means acidic, high pH means basic. The $y$ axis is a measured by volts which may not be intuitive, but let's assume that higher values mean that there's more oxygen around and lower values mean that there's less oxygen around.

As you can see, the lower left area of the diagram is dominated by soluble ferrous iron (all the 2+ you see in there) whereas the top right is dominated by ferric iron. You may notice that there is no hematite here and magnetite only exists at the bottom right, but that's because this diagram is for water saturated ambient conditions. The important thing is where you get the ferric and ferrous iron.

Igneous, metamorphic and some sedimentary rocks have an oxygen fugacity (another measure of how much oxygen is around) that results in most of the iron being ferrous, and some being ferric. This is why in these rocks you end up having ferrous iron bearing minerals (olivine, amphiboles, pyroxenes, biotite) and some ferrous+ferric iron bearing minerals (such magnetite). Once you expose those minerals to the surface, where there's loads of oxygen around from the atmosphere, you oxidise the ferrous to ferric iron, and you get hematite instead. Basically, the rocks begin to rust.

Now, there are some processes where buried rocks can get highly oxidised, thus precipitating hematite, but that's not too common. It does happen though, and when it does it usually has something to do with groundwater (which are rather oxidised). Notice that according to the diagram, sometimes you don't need the system to be that much oxidised if it's basic enough (in terms of pH).

There's also this open access paper that talks about conversion of magnetite to hematite:

Jing Zhao, Joël Brugger, Allan Pring, Mechanism and kinetics of hydrothermal replacement of magnetite by hematite, Geoscience Frontiers, Volume 10, Issue 1, 2019, Pages 29-41,
https://doi.org/10.1016/j.gsf.2018.05.015.