The documented history of Madrid dates to the 9th century, although the area has been inhabited since prehistoric times. The development of Madrid as a city began when Philip II moved his court there from Toledo in the 1560s. Madrid has been the country's capital continuously since 1606.

There are several theories regarding the origin of the name "Madrid".[citation needed] According to legend, Madrid was founded by Ocno Bianor (son of King Tyrrhenius of Tuscany and Mantua) and was named "Metragirta" or "Mantua Carpetana". Others contend that the original name of the city was "Ursaria" ("land of bears" in Latin), because of the many bears that were to be found in the nearby forests, which, together with the strawberry tree (Spanish madroño), have been the emblem of the city from the Middle Ages.[1]

The most ancient recorded name of the city "Magerit" (for *Materit or *Mageterit?) comes from the name of a fortress built on the Manzanares River in the 9th century AD, and means "Place of abundant water".[2] If the form is correct, it could be a Celtic place-name from ritu- 'ford' (Old Welsh rit, Welsh rhyd, Old Breton rit, Old Northern French roy) and a first element, that is not clearly identified *mageto derivation of magos 'field, plain' (Old Irish mag 'field', Breton ma 'place'), or matu 'bear', that could explain the Latin translation Ursalia.[3]

Nevertheless, it is now commonly believed[citation needed] that the origin of the current name of the city comes from the 2nd century BC. The Roman Empire established a settlement on the banks of the Manzanares river. The name of this first village was "Matrice" (a reference to the river that crossed the settlement). Following the invasions carried out by the Germanic Sueves and Vandals, as well as the Sarmatic Alans during the 5th century AD, the Roman Empire no longer had the military presence required to defend its territories on the Iberian Peninsula.[4]

As a consequence, these territories were soon occupied by the Vandals, who were in turn dispelled by the Visigoths, who then ruled Hispania in the name of the Roman emperor, also taking control of "Matrice". In the 8th century, the Islamic conquest of the Iberian Peninsula saw the name changed to "Mayrit", from the Arabic term ميرا Mayra (referencing water as a 'tree' or 'giver of life') and the Ibero-Roman suffix it that means 'place'. The modern "Madrid" evolved from the Mozarabic "Matrit", which is still in the Madrilenian gentilic.[4]

The site of modern-day Madrid has been occupied since prehistoric times, and archaeological research found a small Visigothic village nearby.[5]

In the mid-9th century, Muhammad I of Córdoba constructed a small castle where the Palacio Real stands today. The Moors built a citadel, al-Mudayna, around this castle. They named the area after the nearby Manzanares River, which the Muslims called al-Majrīṭ (Arabic: المجريط "source of water"). From this came the name Majerit, later spelled Madrid.

Leo ruled for only a few years. Later, Henry III of Castile (1379–1406) rebuilt the city after it was destroyed by fire, and founded El Pardo just outside its walls. The kingdom of Castile controlled the city until the death of King Henry VI of England, when the kingdom of Aragon disputed the succession. The marriage of Ferdinand and Isabella united the Crowns of Castile and Aragon, leading to the beginnings of modern Spain, though the two kingdoms retained their own national laws for a time, until 1714, when under the new Dinasty of the Bourboun a centralised State was built under the "ways and laws of Castile".

The kingdoms of Castile and Aragón were fully united by Charles I of Spain (otherwise known as the Holy Roman Emperor Charles V). Though Charles favored Seville, his son, Philip II (1527–1598) moved the court to Madrid in 1561. Although he made no official declaration, the seat of the court became the de facto capital. Aside from a brief period from 1601–1606 when King Philip III installed his court in Valladolid, Madrid's fortunes have closely mirrored those of Spain.

During the 17th century, Spain's Siglo de Oro (Golden Century), Madrid grew rapidly. The royal court attracted many of Spain's leading artists and writers to Madrid, including Cervantes, Lope de Vega, and Velázquez.

View of Madrid from the west, facing the Puerta de la Vega (1562), by Anton Van der Wyngaerde (known in Spanish as Antonio de las Viñas), commissioned by Philip II to collect views of his cities. The banks of the Manzanares can be seen in the foreground, crossed by the predecessors to the present-day Segovia Bridge (in the first third) and the Toledo Bridge (further south, right), which was rebuilt in a monumental form years later. The most prominent building in the north (left) is the Alcázar, which was part of the city wall and would suffer several fires until it was almost completely destroyed in 1734 and was replaced by the current Palacio Real. Several churches can be seen, but without the domes and chapiters by which they would be characterized in the following centuries. By the river, there is a facility for the treatment of hides: the Pozacho tanneries. The recent installation of the court had imposed a regalía de aposento tax on private houses, which led to all kinds of resistance including, most notably, the construction of casas a la malicia.[7]

In 1739 Philip V began constructing new palaces, including the Palacio Real de Madrid. Under Charles III (1716–1788) that Madrid became a truly modern city. Charles III, who cleaned up the city and its government, became one of the most popular kings to rule Madrid, and the saying "the best mayor, the king" became widespread. Besides completing the Palacio Real, Charles III is responsible for many of Madrid's finest buildings and monuments, including the Prado and the Puerta de Alcalá.

On 27 October 1807, Charles IV and Napoleon signed the Treaty of Fontainebleau, which allowed French troops passage through Spanish territory to join Spanish troops and invade Portugal, which had refused to obey the order for an international blockade against England. In February 1808, Napoleon used the excuse that the blockade against England was not being respected at Portuguese ports to send a powerful army under his brother-in-law, General Joachim Murat. Contrary to the treaty, French troops entered via Catalonia, occupying the plazas along the way. Thus, throughout February and March of 1808, cities like Barcelona and Pamplona remained under French rule.

While all this was happening, the Mutiny of Aranjuez (17 March 1808) took place, led by Charles IV's own son, crown prince Ferdinand, and directed against him. Charles IV resigned and Ferdinand took his place as King Ferdinand VII. In May 1808 Napoleon's troops entered the city. On 2 May 1808 (Spanish: Dos de Mayo) the Madrileños revolted against the French forces, whose brutal behavior would have a lasting impact on French rule in Spain and France's image in Europe in general. Thus Ferdinand VII returned to a Madrid that had been occupied by Murat.[8]

Both the king and his father became virtual prisoners of the French army. Napoleon, taking advantage of the weakness of the Bourbons, forced both, first the father and then the son, to meet him at Bayonne, where Ferdinand VII arrived on 20 April. Here Napoleon forced both kings to abdicate on 5 May, handing the throne to his brother Joseph Bonaparte.

On 2 May, the crowd began to concentrate at the Palacio Real and watched as the French soldiers removed the royal family members from the palace. On seeing the infanteFrancisco de Paula struggling with his captor, the crowd launched an assault on the carriages, shouting ¡Que nos lo llevan! (They're taking him away from us!). French soldiers fired into the crowd. The fighting lasted for hours and is reflected in Goya's painting, The Second of May 1808, also known as The Charge of the Mamelukes.

Meanwhile, the Spanish military remained garrisoned and passive. Only the artillery barracks at Monteleón under Captain Luis Daoíz y Torres, manned by four officers, three NCOs and ten men, resisted. They were later reinforced by a further 33 men and two officers led by Pedro Velarde y Santillán, and distributed weapons to the civilian population.[9] After repelling a first attack under French General Lefranc, both Spanish commanders died fighting heroically against reinforcements sent by Murat. Gradually, the pockets of resistance fell. Hundreds of Spanish men and women and French soldiers were killed in this skirmish.

After the war of independence Ferdinand VII returned to the throne (1814), but after a liberal military revolution, Colonel Riego made the king swear to respect the Constitution. Liberal and conservative government thereafter alternated, ending with the enthronement of Isabella II (1830–1904). She could not calm down the political tension that would lead to yet another revolt, the First Spanish Republic, and the comeback of the monarchs, and eventually to the Second Spanish Republic and the Spanish Civil War.

The military uprising of July 1936 was defeated in Madrid by a combination of loyal police units and workers' militias. After this, from 1936–1939, Madrid was held by forces loyal to the Spanish Republic and was besieged by Spanish Nationalist and allied troops under Francisco Franco. Madrid, besieged from October 1936, saw a pitched battle in its western suburbs in November of that year and eventually fell to the nationalists on 28 March 1939. The Siege of Madrid saw the first mass bombing of civilians from the air by the German Condor Legion.[citation needed]

During the dictatorship of Francisco Franco, especially after the sixties, the south of Madrid became very industrialized and experienced massive migrations from rural environments into the city. Madrid's south-eastern periphery became an extensive slum settlement, which was the base for an active cultural and political life.

Following the death of Franco, and in order to secure stability and democracy, the emerging democratic parties (including those of left-wing and republican ideology) accepted Franco's wish to be succeeded by Juan Carlos I, leading to Spain's current position as a constitutional monarchy.

Benefiting from prosperity in the 1980s, Spain's capital city has consolidated its position as the leading economic, cultural, industrial, educational and technological center of the Iberian peninsula.