A city already existed at this site during the time of the Phoenicians and Romans, but was destroyed during the Arab conquest of North Africa. Mahdia was founded by the Fatimids under the Caliph Abdallah al-Mahdi in 921 and named after their self-proclaimed Mahdi, and made the capital city of Ifriqiya, by caliph Abdallah El Fatimi. It was chosen the capital because of its proximity to the sea, and the promontory on which an important military settlement had been since the time of the Phoenicians. In 1087 the town was attacked by raiding ships from Genoa and Pisa. The Zirid dynasty had its residence here in the 11th century, but was brought to an end by the Norman conquest of the city in 1148. In 1160 the city comes under Almohad rule.
The role of the capital was taken over by Tunis in the 13th century during the Hafsid Dynasty. Some buildings still exist from the 10th and 11th centuries, such as the Great Mosque and the Casbah, which have helped make the city an important tourist attraction.