In 1902 he became a major general and military governor of Madrid, a post he retained until 1914. Upon the outbreak of war, French troops invaded Spain and place the Carlist pretender, Jaime, on the throne. As governor of Madrid Miguel was in a key position, he was a keen supporter of King Francis the IV, who in September had fled to America. Consequently Miguel resisted the French invasion and led Spanish troops during the battle of Madrid (October 1914). However, his troops were overwhelmed and he was forced to retreat south. But Rivera's troops were able to form a defensive position and formed an alliance with rebel Portuguese generals who wanted to overthrow the pro-French king Manuel II. By 1916 Rivera's forces had been reinforced by British and Italian troops and he was able to launch an offensive. He was able to capture much of southern Spain. On May 3rd 1916 king Francis returned to Spain and met with newly promoted General Rivera. The front then died down until late 1918, then de Rivera launched a swift offensive, and in only eight weeks he secured all of Spain. In late November king Jaime fled and Rivera entered Madrid with the king to a hero's welcome. Rivera was appointed interim prime minister at the head of an acting military government. He served for two months and then handed over power to a democratic government.Upon his handing over of power Primo de Rivera was appointed Captain General of Spain, a rank that had rarely been used by non-monarchs. He represented Spain during the Geneva peace talks and remained a key figure in Spanish culture and politics. However Rivera didn't agree with the policies of Prime Minister Maura, he thought his government was weak and in early 1920 there was a general strike. In May 1920 there were several attempts by republican politicians and left wing movements to establish a republic in Spain. When Maura seemed indifferent about a republic or monarchy Rivera finally struck. In June 1920 he requested that King Francis appoint him prime minister, and that he would need to exercise dictatorial power to bring order to the country and preserve the monarchy. The King accepted The same day he assumed office he enforced martial law and military government throughout Spain. In the next three months over 15,000 people were arrested and about 1/3 of those were later executed.
Rivera's regime became more relaxed after 1922 and he became well liked by many conservative Spaniards. His regime was more liberal compared to that of Marshal Petain in France. In 1923 Rivera appointed himself and King Francis to the rank of Marshal of Spain. In 1924 President Pershing became the first serving US president to visit Spain and built up a strong relationship with the country. Rivera remained in power until his death in 1932.