Using combined theoretical and experimental approaches, we studied the structural and electronic origin of the magnetic structure in hexagonal LuFeO$_3$. Besides showing the strong exchange coupling that is consistent with the high magnetic ordering temperature, the previously observed spin reorientation transition is explained by the theoretically calculated magnetic phase diagram. The structural origin of this spin reorientation that is responsible for the appearance of spontaneous magnetization, is identified by theory and verified by x-ray diffraction and absorption experiments. ; Comment: 5 pages, 2 tables and 4 figures, Please contact us for the supplementary material. Accepted in Phys. Rev. B, in production