The cities of Melilla and Ceuta had been Spanish territory since 1497 and 1580 respectively, the latter handed over by Portugal. With the signing of the Treaty of Fez in March 1912, the sovereignty of the majority of Morocco passed to France, which declared the country a protectorate (this was part of a series of international agreements which saw recognition of French and Spanish territories in West Africa and the creation of a German colony Kamerun). A further agreement signed on 27 November 1912 between Spain and France established a Spanish Protectorate over the northern coastal zone which surrounded and joined Melilla and Ceuta, as well as Ifni on the Atlantic coast, and Tangiers (which became an International Zone in 1923).
In 1956 when French Morocco gained independence, Spain surrendered the majority of it's occupied territory - but not Ceuta, Melilla, Ifni, and Tarfaya. Tarfaya was prised back from Spain by Morocco in 1958, and Ifni followed in 1969. Spain, however, considers the cities of Melilla and Ceuta to be part of Spain proper and has refused Moroccan demands to return them.