Anfa became the capital of a Berber principality in the aftermath of the Arab invasions of the 7th and 8th centuries. The Berbers embraced Islam but quickly succumbed to heretical doctrines, setting up their own prophet and a Qur’an in Berber language.
The principality was known as Berghouata, and its tribal inhabitants joined a Kharijite rebellion against the Arab governor of Tangier. In the 11th century, the Almoravids waged holy war against these heretics, who were finally defeated by the Almohad Sultan Abdul Mou’min.
The town came under the influence of the Merenids during the 13th century, but eventually became independent as the dynasty weakened.
The Portuguese destroyed the town in 1468 in reprisal for piracy. Portugal sent a fleet of 50 vessels and 10,000 soldiers to occupy the town, which was sacked and then abandoned. But piracy soon revived, and the Portuguese returned in 1515 and destroyed the town once again.
In 1575, the town was rebuilt, fortified, and renamed Casa Branca by the Portuguese in an attempt to establish control over the area. However, the Portuguese rulers fell under constant attack by surrounding Muslim tribes and were finally forced to abandon the town following a terrible earthquake in 1755.
Under the reign of Sidi Mohamed ben Abdallah (1757-1790), the town was rebuilt with a mosque, madrasa, hammam, and a fort and renamed Dar El Beida (The White House), which the Spanish eventually translated as Casablanca.