The history of Morocco spans over twelve centuries, without taking Classical antiquity into consideration. The territory that now constitutes Morocco has been inhabited by Berbers for over 5000 years. The country was first unified by the Idrisid dynasty in 789, half a century after the Berber Revolt, that led to its independence from the Arab Caliphate. Under the Almoravid dynasty and the Almohad dynasty, Morocco dominated the Maghreb and Muslim Spain. The Reconquista endedrule in Iberia and many Muslims and Jews migrated to Morocco. Under the Saadi dynasty, Morocco consolidated power and fought off Portuguese and Ottoman invaders, as was the case in the battle of Ksar el Kebir.
The reign of Ahmad al-Mansur brought forth new wealth and prestige to the Sultanate, and an invasion of the Songhai Empire was initiated. However, managing the territories across the Sahara proved to be difficult. After the death of al-Mansur the country was divided among his sons. In 1666 the sultanate was reunited by the Alaouite dynasty, who have since been the ruling house of Morocco. The organization of the state developed with Ismail Ibn Sharif. With his Black Guard he drove the English from Tangier in 1684 and the Spanish from Larache in 1689. The Alaouite dynasty distinguished itself in the 19th century by maintaining Moroccan independence, while other states in the region succumbed to European interests. In 1912, after the First Moroccan Crisis and the Agadir Crisis, the Treaty of Fez was signed, effectively dividing Morocco into a French and Spanish protectorate. In 1956, after 44 years of occupation, Morocco regained independence from France as the Kingdom of Morocco.