Tension between Morocco and France developed after the French conquest of Algeria in 1830. The Moroccan sultan, Abd ar-Rahman, sent his army to occupy the Algerian city of Tlemcen, but withdrew under pressure from the French. The Algerian resistance leader, Abdel Kadir, took refuge in Morocco in 1844. The French bombarded the coastal cities of Tangier and Essaouira and engaged the Moroccan army in a battle near the inland town of Oujda. When Morocco was soundly defeated in this battle, its sultan was forced to agree to expel Abdel Kadir.
Morocco also found itself in conflict with Spain. Spain controlled the port city of Ceuta, in Morocco just across the Straits of Gibraltar from Spain itself. Following a disagreement over the boundaries of Ceuta in 1859, Morocco and France went to war. Once again, the European nation, which had a more modern military, won. Morocco paid a heavy indemnity, or fine, and gave Spain its port city of Sidi Ifni on the Atlantic coast.
In the late nineteenth century, the Moroccans attempted to modernize their military and their government system in order to meet the growing European threat. In 1901 a young sultan, Abd-el-Aziz, attempted to introduce a system of taxation of land. He also adopted many European customs in his own life and relied heavily on foreign advisers. However, his introduction of European, non-Muslim influences angered Muslim religious leaders. A 1906 international conference in the Spanish city of Algeciras recognized the independence of Morocco but also acknowledged Spanish and French control over Moroccan ports.
In 1907 a brother of Abd-el-Aziz, Abd al-Hafid, raised a revolt against the sultan. Abd al-Hafid became sultan himself but could not control the disorders created in part by the revolt. After requesting French help, he agreed to allow Morocco to become a French protectorate in 1912. Thereafter, Morocco was independent only in name, while under the guidance and control of France.