History of Gibraltar



The history of Gibraltar, a small peninsula on the southern Iberian coast near the entrance of the Mediterranean Sea, spans over 2,900 years. The peninsula has evolved from a place of reverence in ancient times into "one of the most densely fortified and fought-over places in Europe", as one historian has put it. Gibraltar's location has given it an outsized significance in the history of Europe and its fortified town, established in medieval times, has hosted garrisons that sustained numerous sieges and battles over the centuries.

Gibraltar was first inhabited over 50,000 years ago by Neanderthals and may have been one of their last places of habitation before they died out around 24,000 years ago. Gibraltar's recorded history began around 950 BC with the Phoenicians, who lived nearby. The Carthaginians and Romans later worshipped Hercules in shrines said to have been built on the Rock of Gibraltar, which they called Mons Calpe, the "Hollow Mountain", and which they regarded as one of the twin Pillars of Hercules.

Gibraltar became part of the Visigothic Kingdom of Hispania following the collapse of the Roman Empire and came under Muslim Moorish rule in 711 AD. It was permanently settled for the first time by the Moors and was renamed Jebel Tariq – the Mount of Tariq, later corrupted into Gibraltar. The Christian Kingdom of Castile annexed it in 1309, lost it again to the Moors in 1333 and finally regained it in 1462. Gibraltar became part of the unified Kingdom of Spain and remained under Spanish rule until 1704. It was captured during the War of the Spanish Succession by an Anglo-Dutch fleet in the name of Charles VI of Austria, the Habsburg pretender to the Spanish throne. At the war's end, Spain ceded the territory to Britain under the terms of the Treaty of Utrecht of 1713.

Spain tried to regain control of Gibraltar, which Britain had declared a Crown colony, through military, diplomatic and economic pressure. Gibraltar was besieged and heavily bombarded during three wars between Britain and Spain but the attacks were repulsed on each occasion. By the end of the last siege, in the late 18th century, Gibraltar had faced fourteen sieges in 500 years. In the years after Trafalgar, Gibraltar became a major base in the Peninsular War. The colony grew rapidly during the 19th and early 20th centuries, becoming one of Britain's most important possessions in the Mediterranean. It was a key stopping point for vessels en route to India via the Suez Canal. A large British naval base was constructed there at great expense at the end of the 19th century and became the backbone of Gibraltar's economy.

British control of Gibraltar enabled the Allies to control the entrance to the Mediterranean during the Second World War. It was attacked on several occasions by German, Italian and Vichy French forces, though without causing much damage. The Spanish dictator General Francisco Franco declined to join a Nazi plan to occupy Gibraltar but revived Spain's claim to the territory after the war. As the territorial dispute intensified, Spain closed its border with Gibraltar between 1969 and 1985 and communications links were severed. Spain's position was supported by Latin American countries but was rejected by Britain and the Gibraltarians themselves, who vigorously asserted their right to self-determination. Discussions of Gibraltar's status have continued between Britain and Spain but have not reached any conclusion.

Since 1985, Gibraltar has undergone major changes as a result of reductions in Britain's overseas defence commitments. Most British forces have left the territory, which is no longer seen as a place of major military importance. Its economy is now based on tourism, financial services, shipping and Internet gambling. Gibraltar is largely self-governed, with its own parliament and government, though the UK maintains responsibility for defence and foreign policy. Its economic success has made it one of the wealthiest areas of the European Union.

Geographical background
The history of Gibraltar has been driven by its strategic position near the entrance of the Mediterranean Sea. It is a narrow peninsula at the eastern side of the Bay of Gibraltar, 4 mi from the city of Algeciras. Gibraltar is on the far south coast of Spain at one of the narrowest points in the Mediterranean, only 15 mi from the coast of Morocco in North Africa. Its position on the bay makes it an advantageous natural anchorage for ships. As one writer has put it, "whoever controls Gibraltar also controls the movement of ships into and out of the Mediterranean. In terms of military and naval power, few places have a more strategic location than Gibraltar."

The territory's area measures only 2.6 sqmi. Most of the land area is occupied by the steeply sloping Rock of Gibraltar which reaches a height of 426 m. The town of Gibraltar lies at the base of the Rock on the west side of the peninsula. A narrow, low-lying isthmus connects the peninsula to the Spanish mainland. The North Face of the Rock is a nearly vertical cliff 396 m high overlooking the isthmus; the only land access to the town is via a coastal strip about 350 m wide, which was considerably narrower before the reclamation of land from the sea during the 20th century.

Gibraltar's geography has thus given it considerable natural defensive advantages. It is virtually impossible to scale the eastern or northern sides of the Rock, which are either vertical or nearly so. To the south, the relatively flat area around Europa Point is surrounded by cliffs which are up to 30 m high. The western side is the only practicable area for a landing, but even here the steep slopes on which the town is built work to the advantage of a defender. These factors have given it an enormous military significance over the centuries.

Prehistory and ancient history


Gibraltar's appearance in prehistory was very different. Whereas today it is surrounded by sea, the water level was much lower in prehistoric times, when the polar ice caps were larger. The current peninsula was surrounded by a fertile coastal plain, with marshes and sand dunes supporting an abundant variety of animals and plants.

Neanderthals are known to have lived in caves around the Rock of Gibraltar; in 1848 the first known adult Neanderthal skull, and only the second Neanderthal fossil ever found, was excavated at Forbes' Quarry on the north face of the Rock. Had the skull been recognised for what it was, the species might have been named Gibraltarians rather than Neanderthals. The date of the skull is unclear but it has been attributed to around the start of the last glacial period about 50,000 years ago.

More Neanderthal remains have been found elsewhere on the Rock at Devil's Tower and in Ibex, Vanguard and Gorham's Caves on the east side of Gibraltar. Excavations in Gorham's Cave have found evidence of Neanderthal occupation dated as recently as 28,000–24,000 years ago, well after they were believed to have died out elsewhere in Europe. The caves of Gibraltar continued to be used by Homo sapiens after the final extinction of the Neanderthals. Stone tools, ancient hearths and animal bones dating from around 40,000 years ago to about 5,000 years ago have been found in deposits left in Gorham's Cave. Numerous potsherds dating from the Neolithic period have been found in Gibraltar's caves, mostly of types typical of the Almerian culture found elsewhere in Andalusia, especially around the town of Almería, from which it takes its name. There is little evidence of habitation in the Bronze Age, when people had largely abandoned the tradition of living in caves.

During ancient times, Gibraltar was regarded by the peoples of the Mediterranean as a place of religious and symbolic importance. The Phoenicians were present for several centuries, apparently using Gorham's Cave as a shrine to the genius loci of the place, as did the Carthaginians and Romans after them. Excavations in the cave have shown that pottery, jewellery and Egyptian scarabs were left as offerings to the gods, probably in the hope of securing safe passage through the dangerous waters of the Strait of Gibraltar.

The Rock was revered by the Greeks and Romans as one of the two Pillars of Hercules, created by the demigod during his tenth labour when he smashed through a mountain separating the Atlantic and the Mediterranean. According to a Phocaean Greek traveller who visited in the sixth century BC, there were temples and altars to Hercules on the Rock where passing travellers made sacrifices. The Spanish later symbolised the importance of the Pillars of Hercules with a heraldic device consisting of a pair of columns with a scroll wrapped around them – a symbol that became the $ sign and the related Portuguese cifrão.

To the Ancient Romans, Gibraltar was known as Mons Calpe, a name perhaps derived from the Phoenician word kalph, "hollowed out", presumably in reference to the many limestone caves in the Rock. It was well-known to ancient geographers, but there is no known archaeological evidence of permanent settlements from the ancient period. According to the Roman writer Avienus, the ancient Greek traveller Euctemon recorded that

"thirty stadia separate [the Pillars of Hercules]; [Euctemon] says that they bristle with woods all over and are always unwelcoming to seamen. Indeed he says that on those are both temples and altars to Hercules. He says that strangers sail there by boat to make offerings to the gods and depart hot foot thinking it wrong to linger ..."

There were more mundane reasons not to settle, as Gibraltar had many disadvantages that were to hinder later settlers. It lacked easily accessible fresh water, fertile soil or a safe natural anchorage on the shoreline. Avienus cited the "shallow draft and dense mud of the shore" as reasons not to land there. Its geographical location, which later became its key strategic asset, was not a significant factor during the Classical period as the entrance to the Mediterranean was not contested by the states of the day.

For these reasons the ancients instead settled at the head of the bay in what is today known as the Campo (hinterland) of Gibraltar. The town of Carteia, near the location of the modern Spanish town of San Roque, was founded by the Phoenicians around 950 BC on the site of an early settlement of the native Turdetani people. The Carthaginians took control of the town by 228 BC and it was captured by the Romans in 206 BC. It subsequently became Pompey's western base in his campaign of 67 BC against the pirates that menaced the Mediterranean Sea at the time. Carteia appears to have been abandoned after the Vandals sacked it in 409 AD during their march through Roman Hispania to Africa. The region subsequently fell under the rule of the Christianised Visigoths.

Muslim rule (711–1309, 1333–1462)
By 681 the armies of the Umayyad Caliphate had expanded from their original homeland of Arabia to conquer North Africa, the Middle East and large parts of West Asia, bringing Islam in their wake and converting local peoples to the new religion. The Berbers of North Africa, called Moors by the Christians, thereby became Muslims. The Strait of Gibraltar became the frontier between Muslim North Africa and Christian Hispania and thus gained a new strategic significance. Hispania descended into civil war in the 8th century as rival Visigothic factions fought for control of the throne. This gave the Moors the opportunity to invade Hispania and pursue a course of dividing-and-conquering the Christian factions.

Following a raid in 710, a predominately Berber army under the command of Tariq ibn Ziyad crossed from North Africa in April 711 and landed somewhere in the vicinity of Gibraltar (though most likely not in the bay or at the Rock itself). Although Tariq's expedition was an outstanding success and led to the Islamic conquest of most of the Iberian peninsula, he ended his career in disgrace after falling out with the Arab general Musa bin Nusayr. His conquest nonetheless left a long-lasting legacy for Gibraltar: Mons Calpe was renamed Jebel Tariq, the Mount of Tariq, subsequently corrupted into Gibraltar.

Gibraltar was fortified for the first time in 1160 by the Almohad Sultan Abd al-Mu'min in response to the coastal threat posed by the Christian kings of Aragon and Castile. Gibraltar was renamed Jebel al-Fath (the Mount of Victory), though this name did not persist, and a fortified town named Medinat al-Fath (the City of Victory) was laid out on the upper slopes of the Rock. It is unclear how much of Medinat al-Fath was actually built, as the surviving archaeological remains are scanty.

In the late thirteen and early fourteenth centuries Castile fought with the Marinids of Morocco and the Nasrids of Granada for control of the Strait of Gibraltar. This conflict (la Cuestión del Estrecho) is a major chapter in the history of the Christian reconquest of Spain. Although no documentary account of Gibraltar is available for the period following the creation of Madinat al-Fath, there are reasons to believe that a small fortified town existed in Gibraltar, and that its existence was the direct consequence of the fall of Tarifa in 1292. After the capture of the city, it was expected that the Castilian king Sancho IV would lay siege to Algeciras (though in the event, he did not do so) in order to hinder the Marinids' communications with the Iberian peninsula. The threatening presence of a Christian stronghold to the west would have made it necessary to set up a garrison to the east of Algeciras. That way, Gibraltar would protect the rearguard of Algeciras and provided a fallback position if the town fell. At the same time, the heights of the Rock of Gibraltar provided an excellent vantage point for monitoring the activities of the Christian fleets in the Straits.

It was not until 1309 when Gibraltar's defences were put to the test for the first time in the First Siege of Gibraltar. That year Ferdinand IV of Castile and James II of Aragon joined forces to attack the Muslim Emirate of Granada, targeting Almería in the east and Algeciras, across the bay from Gibraltar, in the west. In July 1309 the Castilians laid siege to both Algeciras and Gibraltar. By this time the latter had a modest population of around 1,200 people, a castle and rudimentary fortifications. They proved unequal to the task of keeping out the Castilians and Gibraltar's Nasrid defenders surrendered after a month. Ferdinand gave up the siege of Algeciras the following February but held on to Gibraltar, expelling the Moors and repopulating it with Christians. A keep and dockyard were built on his orders to secure Castile's hold on the peninsula. Ferdinand also issued a letter patent granting privileges to the inhabitants to encourage people to settle, as it was initially not regarded as a particularly hospitable place to live. In 1315 the Nasrid Moors of Granada attempted to recapture Gibraltar but abandoned a brief siege when a Castilian relief force appeared. Eighteen years later, the Nasrid Sultan of Granada, Muhammed and the Marinid Sultan of Fez, Abu al-Hasan Ali ibn Othman, united to besiege Gibraltar with a large army and naval force. This time the king of Castile, Alfonso XI, was unable to raise a relief force for several months because of the threat of rebellions within his kingdom. The relief force eventually arrived in June 1333 but found that the starving inhabitants of Gibraltar had already surrendered to the Moors of Fez. The Castilians now found themselves having to besiege an entrenched enemy, but they were unable to break through the Moorish defences and, faced with a stalemate, the two sides agreed to disengage in exchange for mutual concessions and a four-year truce.

Abu al-Hasan refortified Gibraltar with what the Arab chroniclers called "strong walls as a halo surrounds a crescent moon" in anticipation of renewed war, which duly broke out in 1339. However, his forces suffered a disastrous defeat at the Battle of Río Salado in October 1340 and fell back to Algeciras. The Castilians besieged the city for two years and eventually forced its surrender, though Gibraltar remained in Moorish hands. The peninsula's defences had been greatly improved by Abu al-Hasan's construction of new walls, towers, magazines and a citadel, making its capture a much more difficult endeavour. Alfonso XI once again laid siege in 1349 following the death of Abu al-Hasan but was thwarted by the arrival of the Black Death in 1350, which killed many of his soldiers and claimed his own life.

Gibraltar remained in Moorish hands until 1462 but was disputed between the Nasrids of Granada and Marinids of Fez. In 1374 the latter handed the peninsula to the former, apparently in payment for Granadan military support in suppressing rebellions in Morocco. Gibraltar's garrison rebelled against the Nasrids in 1410 but a Granadan army retook the place the following year after a brief siege. Gibraltar was subsequently used by the Granadans as the base for raids into Christian territory, prompting Enrique de Guzmán, second Count of Niebla, to lay siege in 1436. The attempt ended in disaster; the attack was repelled with heavy casualties and Enrique himself was drowned while trying to escape by sea. His body was recovered by the Moors, decapitated and hung on the walls of Gibraltar for the next twenty-two years.

Moorish rule over Gibraltar came to an end in August 1462 when a small Castilian force under the command of Alonso de Arcos, the governor of Tarifa, launched a surprise attack. The Castilians mounted their attack while Gibraltar's senior commanders and townspeople were away paying homage to the new sultan of Granada. After a short assault which inflicted heavy losses on the defenders, the garrison surrendered to Enrique de Guzmán's son Juan Alonso, now the first Duke of Medina Sidonia. The Moorish inhabitants were once again expelled en masse, to be replaced by Christians.

Castilian and Spanish rule (1462–1704)
Shortly after Gibraltar's recapture, King Henry IV of Castile declared it Crown property and reinstituted the special privileges which his predecessor had granted during the previous period of Christian rule. Four years after visiting Gibraltar in 1463, he was overthrown by the Spanish nobility and clergy. His half-brother Alfonso was declared king and rewarded Medina Sidonia for his support with the lordship of Gibraltar. The existing governor, a loyalist of the deposed Henry IV, refused to surrender Gibraltar to Medina Sidonia. After a fifteen-month siege from April 1466 to July 1467, Medina Sidonia took control of the town. He died the following year but his son Enrique was confirmed as lord of Gibraltar by the reinstated Henry IV in 1469. In 1474 the new Duke of Medina Sidonia sold Gibraltar to a group of Jewish conversos from Cordova and Seville led by Pedro de Herrera in exchange for maintaining the garrison of the town for two years, after which time the 4,350 conversos were expelled by the Duke. His status was further enhanced by Isabella I of Castile in 1478 with the granting of the Marquisate of Gibraltar.

On 2 January 1492, after five years of war, the Moorish emirate in Spain came to an end with the Catholic Monarchs' capture of Granada. The Jews of Gibraltar were, like those elsewhere in the kingdom, expelled from Spain by order of the monarchs in March that year. Gibraltar was used by Medina Sidonia as a base for the Spanish capture of Melilla in North Africa in 1497. Two years later the remaining Moors of Granada were ordered to convert to Christianity or be expelled. Although some did convert, most left for North Africa, many of them travelling via Gibraltar.

Gibraltar became Crown property again in 1501 at the order of Isabella and the following year it received a new set of royal arms, which is still used by modern Gibraltar, replacing those of Medina Sidonia. In the Royal Warrant accompanying the arms, Isabella highlighted Gibraltar's importance as "the key between these our kingdoms in the Eastern and Western Seas [the Mediterranean and Atlantic]". The metaphor was represented on the royal arms by a golden key hanging from the front gate of a battlemented fortress. The warrant charged all future Spanish monarchs to "hold and retain the said City for themselves and in their own possession; and that no alienation of it, nor any part of it, nor its jurisdiction ... shall ever be made from the Crown of Castile."

At this point in history, "Gibraltar" meant not just the peninsula but the entire surrounding area including the land on which the towns of La Línea de la Concepción, San Roque, Los Barrios and Algeciras now stand. To the east, Gibraltar was bounded by the Guadiaro River, and its northern boundaries lay in the vicinity of Castellar de la Frontera, Jimena de la Frontera, Alcalá de los Gazules, Medina-Sidonia and Tarifa. From the 16th century, the modern meaning of the name came to be adopted – specifically referring only to the town of Gibraltar and the peninsula on which it stands.

Under Spanish Crown rule, the town of Gibraltar fell into severe decline. The end of Muslim rule in Spain and the Christian capture of the southern ports considerably decreased the peninsula's strategic value. It derived some minor economic value from tuna-fishing and wine-producing industries but its usefulness as a fortress was now limited. It was effectively reduced to the status of an unremarkable stronghold on a rocky promontory and Marbella replaced it as the principal Spanish port in the region.

Gibraltar's inhospitable terrain made it an unpopular place to live. To boost the population, convicts from the kingdom of Granada were offered the possibility of serving their sentence in the Gibraltar garrison as an alternative to prison. Despite its apparent unattractiveness, Juan Alfonso de Guzmán, third Duke of Medina Sidonia, nonetheless sought to regain control of the town. In September 1506, following Isabella's death, he laid siege in the expectation that the gates would quickly be opened to his forces. This did not happen, and after a fruitless four-month blockade he gave up the attempt. Gibraltar received the title of "Most Loyal" from the Spanish crown in recognition of its faithfulness.

Barbary pirate raids and wars with other European powers
Despite continuing external threats Gibraltar was neglected by the Spanish crown and its fortifications fell into disrepair. Barbary pirates from North Africa took advantage of the weak defences in September 1540 by mounting a major raid in which hundreds of Gibraltar's residents were taken as hostages or slaves. The Shrine of Our Lady of Europe was sacked and all its valuables were stolen. Many of the captives were subsequently released when a Spanish fleet commanded by Bernardino de Mendoza intercepted the pirate ships near Alborán as they were bringing ransomed hostages back to Gibraltar. The Spanish crown belatedly responded to Gibraltar's vulnerability by building the Charles V Wall to control the southern flank of the Rock and commissioning the Italian engineer Giovanni Battista Calvi to strengthen other parts of the fortifications.

The seas around Gibraltar continued to be dangerous for decades to come as Barbary pirate raids continued; although a small squadron of Spanish galleys was based at the port to counter pirate raids, it proved to be of limited effectiveness and many inhabitants were abducted and sold into slavery by the pirates. The problem worsened significantly after 1606, when Spain expelled its entire population of 600,000 Moriscos – Moors who had converted to Christianity. Many of the expellees were evacuated to North Africa via Gibraltar but ended up joining the pirate fleets, either as Christian slaves or reconverted Muslims, and raided as far afield as Cornwall.

The threat of the Barbary pirates was soon joined by that of Spain's enemies in northern Europe. On 5 May 1607, during the Eighty Years' War, a Dutch fleet under Admiral Jacob van Heemskerk ambushed a Spanish fleet at anchor in the Bay of Gibraltar. The Dutch won an overwhelming victory in the Battle of Gibraltar (1607), losing no ships and very few men while the entire Spanish fleet was destroyed with the loss of 3,000 men. The Spanish and Dutch declared a temporary truce in 1609 (the Twelve Years' Truce) and resumed hostilities in 1621, when a joint Dutch and Danish fleet arrived in the Strait to attack Spanish shipping. This time the Spanish succeeded in capturing and sinking a number of the attackers' ships in the Battle of Gibraltar (1621), driving away the rest.

An English military presence was briefly established at Gibraltar for the first time in 1620. The Spanish granted permission for the English fleet to use Gibraltar's port as a base for operations against the Barbary pirates, who were raiding the British and Irish coasts. Some in England had ambitions to turn the fleet against Spain rather than the Barbary coast. However, James I successfully resisted Parliamentary pressure to declare war on Spain and the fleet returned to England. After Charles I ascended the throne in 1625, a second English fleet was sent to the region with instructions to "take or spoil a town" on the Spanish coast. Gibraltar was one of the proposed targets on the basis that it was small, could easily be garrisoned, supplied and defended, and was in a highly strategic location. The English fleet instead attacked Cadiz in the belief that its sacking would be more immediately profitable, but the raid turned into a fiasco. The landing force looted the town's wine stores and was evacuated after four days of mass drunkenness without anything useful having been achieved.

The presence of Spain's enemies in the Straits prompted the Spanish king Philip IV to order Gibraltar's defences to be strengthened. A new mole and gun platforms were built, though the latter's usefulness was limited due to a lack of gunners. The town was an unsanitary, crowded place, which probably contributed to the outbreak in 1649 of an epidemic – reportedly plague but possibly typhoid – which killed a quarter of the population. English fleets returned to Gibraltar in 1651–52 and again in 1654–55 as temporary allies of the Spanish against French and Dutch shipping in the Straits.

In 1654, Oliver Cromwell decided to turn on Spain (which had been the first state to recognise the Commonwealth of England) and seize the island of Hispaniola to make it a base for English expansion in the Caribbean. To do so, two fleets were fitted out: one set out to America and another to the western Mediterranean with the ostensible objective of fighting the Barbary pirates. The fleet in the Caribbean failed to seize Hispaniola but took over Jamaica instead in May 1655. The fleet in the Mediterranean sailed off Cadiz trying to intercept the Spanish treasure fleet with no success. With the arrival of the winter, the fleet went back to England. However, Spain did not declare war on England until February 1656. Shortly after, a fleet of 49 English warships manned by 10,000 sailors and soldiers sailed through the Straits and reconnoitered Gibraltar. Although they lacked a viable landing force and took no action, Oliver Cromwell expressed interest in its capture: "if possessed and made tenable by us, would it not be both an advantage to our trade, and an annoyance to the Spaniards, and enable us [to] ... ease our own charge?" In 1693, during the Nine Years' War, in which Spain and England were allies, the remnants of an English-Dutch escort squadron under the command of Admiral Sir George Rooke took refuge at Gibraltar, pursued by the French, after losing the Battle of Lagos Bay. Eleven years later, Rooke was to return to Gibraltar to capture it.

War of the Spanish Succession (1701–14)
In November 1700, Charles II of Spain died childless. The dispute over who should succeed him – the Bourbon Prince Philip of Anjou, grandson of Louis XIV of France, or the Habsburg Archduke Charles of Austria – soon plunged Europe into a major war. Louis XIV supported Philip. England, the Netherlands, Austria, Portugal, Savoy and some of the German states supported Charles, fearing that Philip's accession would result in French domination of Europe and the Americas. In accordance with Charles II's will, Philip was proclaimed king as Philip V of Spain and allied his new kingdom with France. The following February, the War of the Spanish Succession broke out when French forces arrived in the Spanish Netherlands and expelled the Dutch from the barrier towns. In May 1702, England's Queen Anne formally declared war on France.

Spain thus became a target for the Anglo-Dutch-Austrian alliance. The confederates' campaign was pursued by land and by sea. The main land offensive was pursued in the Low Countries by the Duke of Marlborough, while naval forces under the command of Admiral Sir George Rooke harassed French and Spanish shipping in the Atlantic. In 1703, Marlborough devised a plan under which his forces would launch a surprise attack against the French and their Bavarian allies in the Danube basin while Rooke carried out a diversionary naval offensive in the Mediterranean. Rooke was instructed to attack French or Spanish coastal towns, though the choice of target was left to his discretion.

When Rooke arrived in the region several targets were considered. An attempt to incite the inhabitants of Barcelona to revolt against Philip V failed, and a plan to assault the French naval base at Toulon was abandoned. Casting around for an alternative target, Rooke decided to attack Gibraltar for three principal reasons: it was poorly garrisoned, it would be of major strategic value to the war effort, and its capture might encourage the inhabitants of southern Spain to reject Philip.

The attack was launched on 1 August 1704 as a combined operation between the naval force under Rooke's command and a force of Dutch and English marines under the command of Prince George of Hesse-Darmstadt and Captain Whittaker of HMS Dorsetshire. After a heavy naval bombardment on 2 August, the marines launched a pincer attack on the town, advancing south from the isthmus and north from Europa Point. Gibraltar's defenders were well stocked with food and ammunition but were heavily outnumbered and outgunned. The Spanish position was untenable and on the morning of 4 August, the governor, Diego de Salinas, agreed to surrender.

The terms of surrender made it clear that Gibraltar had been taken in the name of Charles III of Spain, described in the terms as "legitimate Lord and King". The inhabitants and garrison of Gibraltar were promised freedom of religion and the maintenance of existing rights if they wished to stay, on condition that they swore an oath of loyalty to Charles. As had happened two years previously in the raid on Cadiz, the discipline of the landing forces soon broke down. There were numerous incidents of rape, all Catholic churches but one (the Parish Church of St. Mary the Crowned, now the Cathedral) were desecrated or converted into military storehouses, and religious symbols such as the statue of Our Lady of Europe were damaged and destroyed. Angry Spanish inhabitants took violent reprisals against the occupiers. English and Dutch soldiers and sailors were attacked and killed, and their bodies were thrown into wells and cesspits.

When the Spanish garrison marched out on 7 August almost all of the inhabitants, some 4,000 people in total, joined them. They had reason to believe that their exile would not last long, as fortresses changed hands frequently at the time. Many resettled nearby in the ruins of Algeciras or around an old hermitage at the head of the bay. They took with them the records of the city council including Gibraltar's banner and royal warrant. In time the refugee settlement at the hermitage developed into the town of San Roque. It was regarded by the Spanish, as Philip V put it in 1706, as being the "City of Gibraltar resident in its Campo". A small population of around seventy neutral Genoese people stayed behind in Gibraltar.

The confederates' control of Gibraltar was challenged on 24 August when a French fleet entered the Straits. In the subsequent Battle of Vélez-Málaga, both sides sustained heavy crew casualties but lost no ships, enabling each side to claim the engagement as a victory. The French withdrew to Toulon without attempting to assault Gibraltar. In early September a Franco-Spanish army arrived outside Gibraltar and prepared for a siege which they commenced on 9 October. Around 7,000 French and Spanish soldiers, aided by refugees from Gibraltar, were pitted against a force of 2,000 defenders consisting of English and Dutch marines and Spaniards loyal to Charles.

The defenders were aided from late October by a naval squadron under Admiral Sir John Leake. A further 2,200 English and Dutch reinforcements arrived by sea with fresh supplies of food and ammunition in December 1704. With morale falling in the Franco-Spanish camp amid desertions and sickness, Louis XIV despatched Marshal de Tessé to take command in February 1705. A Franco-Spanish assault was beaten back with heavy casualties and on 31 March, de Tessé gave up the siege, complaining of a "want of method and planning".

Gibraltar was now nominally a possession of Charles of Austria but in practice it was increasingly ruled as a British possession. The British commandant, Major General John Shrimpton, was appointed by Charles as Gibraltar's governor in 1705 on the advice of Queen Anne. The Queen subsequently declared Gibraltar a free port at the insistence of the Sultan of Morocco, though she had no formal authority to do so. Shrimpton was replaced in 1707 by Colonel Roger Elliott, who was replaced in turn by Brigadier Thomas Stanwix in 1711; this time the appointments were made directly by London with no claim of authority from Charles. Stanwix was ordered to expel all foreign troops from Gibraltar to secure its status as an exclusively British possession but failed to evict the Dutch, apparently not considering them "foreign".

The War of the Spanish Succession was finally settled in 1713 by a series of treaties and agreements. Under the Treaty of Utrecht, which was signed on 13 July 1713 and brought together a number of sub-treaties and agreements, Philip V was accepted by Britain and Austria as king of Spain in exchange for guarantees that the crowns of France and Spain would not be unified. Various territorial exchanges were agreed: although Philip V retained the Spanish overseas empire, he ceded the Southern Netherlands, Naples, Milan, and Sardinia to Austria; Sicily and some Milanese lands to Savoy; and Gibraltar and Minorca to Great Britain. In addition he granted the British the exclusive right to non-Spanish slave trading in Spanish America for thirty years, the so-called asiento. With regard to Gibraltar (Article X), the town, fortifications and port (but not the hinterland) were ceded to Britain "for ever, without any exception or impediment whatsoever." The treaty also stipulated that if Britain was ever to dispose of Gibraltar it would first have to offer the territory to Spain.

Consolidation and sieges
Despite its later importance to Britain, Gibraltar was initially seen by the British Government as more of a bargaining counter than a strategic asset. Its defences continued to be neglected, its garrisoning was an unwelcome expense, and Spanish pressure threatened Britain's vital overseas trade. On seven separate occasions between 1713 and 1728 the British Government proposed to exchange Gibraltar for concessions from Spain, but on each occasion the proposals were vetoed by the British Parliament following public protests.

Spain's loss of Gibraltar and other Spanish territories in the Mediterranean was resented by the Spanish public and monarchy alike. In 1717 Spanish forces retook Sardinia and in 1718 Sicily, both of which had been ceded to Austria under the Treaty of Utrecht. The effective Spanish repudiation of the treaty prompted the British initially to propose handing back Gibraltar in exchange for a peace agreement and, when that failed, to declare war on Spain. The Spanish gains were quickly reversed, a Spanish expedition to Scotland in 1719 supporting the Jacobites was defeated and peace was eventually restored by the Treaty of The Hague (1720).

In January 1727, Spain declared the nullification of the Treaty of Utrecht's provisions relating to Gibraltar on the grounds that Britain had violated its terms by extending Gibraltar's fortifications beyond the permitted limits, allowing Jews and Moors to live there, failing to protect Catholics and harming Spain's revenues by allowing smuggling. Spanish forces began a siege and bombardment of Gibraltar the following month, causing severe damage through intensive cannon fire. The defenders withstood the threat and were reinforced and resupplied by a British naval force. Bad weather and supply problems caused the Spanish to call off the siege at the end of June. Britain's hold on Gibraltar was reconfirmed in 1729 by the Treaty of Seville, which satisfied neither side; the Spanish had wanted Gibraltar returned, while the British disliked the continuation of the restrictions imposed by the Treaty of Utrecht. Spain responded the following year by constructing a line of fortifications across the upper end of the peninsula, cutting off Gibraltar from its hinterland. The fortifications, known to the British as the Spanish Lines, and to Spain as La Línea de Contravalación (the Lines of Contravallation), were later to give their name to the modern town of La Línea de la Concepción. Gibraltar was effectively blockaded by land but was able to rely on trade with Morocco for food and other supplies.

Gibraltar's civilian population increased steadily through the century to form a disparate mixture of Britons, Genoese, Jews, Spaniards and Portuguese. By 1754 there were 1,733 civilians in addition to 3,000 garrison soldiers and their 1,426 family members, bringing the total population to 6,159. The civilian population increased to 3,201 by 1777, including 519 Britons, 1,819 Roman Catholics (meaning Spanish, Portuguese, Genoese etc.) and 863 Jews. Each group had its own distinctive niche in the fortress. The Spanish historian López de Alaya, writing in 1782, characterised their roles thus:

"The richest mercantile houses are English ... The Jews, for the most part, are shop keepers and brokers ... They have a synagogue and openly practice the ceremonies of their religion, notwithstanding the terms of the Treaty of Utrecht ... The Genoese are traders, but the greater part of them are fishermen, traders and gardeners."

Life for the ordinary soldiers of the garrison was tedious and harsh, with corporal punishment administered for even the most trivial offences. Suicide and desertions were common due to boredom, shortages of food and the poor living conditions. At Middle Hill Battery, guards had to be posted to prevent soldiers from deserting by lowering themselves on ropes down the cliff face. The fortifications of Gibraltar were modernised and upgraded in the 1770s with the construction of new batteries, bastions and curtain walls. The driving force behind this programme was the highly experienced Colonel (later Major General) William Green, who was to play a key role a few years later as chief engineer of Gibraltar. He was joined in 1776 by Lieutenant General George Augustus Elliott, a veteran of earlier wars against France and Spain who took over the governorship of Gibraltar at a key moment.

Britain's successes in the Seven Years' War had left it with expensive commitments in the Americas that had to be paid for and had catalysed the formation of an anti-British coalition in Europe. The British Government's attempt to levy new taxes on the Thirteen Colonies of British America led to the outbreak of the American War of Independence in 1776. Seeing an opportunity to reverse their own territorial losses, France and Spain declared war on Britain and allied with the American revolutionaries.

The Great Siege of Gibraltar lasted from 24 June 1779 to 7 February 1783 and remains one of the longest sieges endured by the British Armed Forces, as well as being one of the longest continuous sieges in history. A combined Spanish and French fleets blockaded Gibraltar from the sea, while on the land side an enormous army was engaged in constructing forts, redoubts, entrenchments, and batteries from which to attack Gibraltar. The Spanish committed increasing number of troops and ships to the siege, postponing the planned invasion of England by the Armada of 1779. The first relief of the siege came in the spring of 1780 when Admiral George Rodney, captured a Spanish convoy off Cape Finesterre and defeated a Spanish fleet at the Battle of Cape St. Vincent, delivering reinforcements of 1,052 men and an abundance of supplies.

The British defenders continued to resist every attempt to capture Gibraltar by assault but supplies again began to run low. On 12 April 1781 Vice Admiral George Darby's squadron of 29 ships of the line escorting 100 store ships from England laden for Gibraltar entered the bay. The Spanish fleet was unable to intercept Darby's relief. The Spanish frustrated by this failure began a barrage of the town causing great panic and terror among the civilian population. Deliberate targeting of civilians was unprecedented at the time and was to continue for 2 years obliterating any architectural heritage from the Spanish period. Unable to starve the garrison out the French and Spanish attempted further attacks by land and sea, the night before the Grand Attack on 27 November 1781, the British garrison filed silently out of their defence works and made a surprise sortie routing the besieging infantry in their trenches and postponed the grand assault on The Rock for some time.

On 13 September 1782 the Bourbon allies launched their great attack; 5190 fighting men both French and Spanish aboard ten of the newly engineered 'floating batteries' with 138 heavy guns, as well as 18 ships of the line, 40 Spanish gunboats and 20 bomb-vessels with a total of 30,000 sailors and marines. They were supported by 86 land guns and 35,000 Spanish and French troops (7,000 –8,000 French) on land intending to assault the fortifications once they had been demolished. The 138 guns opened fire from floating batteries in the Bay and the 86 guns on the land side, directed on the fortifications after weeks of preparatory artillery fire. But the garrison replied with red-hot shot to set fire to and sink the attacker's floating batteries and warships in the Bay. The British destroyed three of the floating batteries, which blew up as the 'red-hot shot' did its job. The other seven batteries were scuttled by the Spanish. In addition 719 men on board the ships (many of whom drowned) were casualties.

In Britain the Admiralty considered plans for a major relief of Gibraltar, opting to send a larger, but slower fleet, rather than a smaller faster one. In September 1782 a large fleet left Spithead under Richard Howe, arriving off Cape St. Vincent on 9 October. The following evening a gale blew up, scattering the Spanish and French fleet allowing Howe to sail unopposed into Gibraltar. A total of 34 ships of the line escorted 31 transport ships which delivered supplies, food, and ammunition. The fleet also brought the 25th, 59th, and 97th regiments of foot bringing the total number of the garrison to over 7,000 Howe then sailed out and fought an indecisive battle with the combined allied fleet before withdrawing to Britain in line with his orders.

The siege was continued for some months longer, but in the spring of 1783 a preliminary peace agreement brought the cessation of hostilities. Finally, in February of 1783 the siege was lifted. The outcome of the Great Siege made it politically impossible for the British government to again consider trading away Gibraltar, even though King George III warned that it would be the source "of another war, or at least of a constant lurking enmity" and expressed his wish "if possible to be rid of Gibraltar ... I shall not think peace complete if we do not get rid of Gibraltar." General Eliott and the garrison were lauded for their heroism, and the tenacity of their defence of Gibraltar acquired, as one writer puts it, "a sort of cult status". The British public acquired "an emotional, albeit irrational, attachment to the place." The reputed impregnability of Gibraltar gave rise to the expression, which is still current today, of something being as "strong as the Rock of Gibraltar".

Gibraltar as a colony
Following the Great Siege, the civilian population of Gibraltar – which had fallen to under a thousand – expanded rapidly as the territory became both a place of economic opportunity and a refuge from the Napoleonic Wars. Britain's loss of North American colonies in 1776 led to much of her trade being redirected to new markets in India and the East Indies. The favoured route to the east was via Egypt, even before the Suez Canal had been built, and Gibraltar was the first British port reached by ships heading there. The new maritime traffic gave Gibraltar a greatly increased role as a trading port. At the same time, it was a haven in the western Mediterranean from the disruption of the Napoleonic Wars. Many of the new immigrants were Genoese people who had fled Napoleon's annexation of the old Republic of Genoa. By 1813 nearly a third of the population consisted of Genoese and Italians. Portuguese made up another 20 per cent, Spaniards 16.5 per cent, Jews 15.5 per cent, British 13 per cent and Minorcans 4 per cent. The young Benjamin Disraeli described the inhabitants of Gibraltar as a mixture of "Moors with costumes as radiant as a rainbow or Eastern melodrama, Jews with gaberdines and skull-caps, Genoese, Highlanders and Spanish." The inhabitants had a clear pecking order, with British officers at the top and Jews at the bottom. The American naval officer Alexander Slidell Mackenzie, writing in 1829, described the market traders and shoppers in what is now John Mackintosh Square:

"The high handed hauteur of his majesty's officer, as he lounges at a corner in utter scorn of the busy crew of bargainers; the supple cit[izen] who bows breast low to him in hope of a node of condescension ... ; a roughknot skipper, accustomed to bang and bully, a little king upon his own quarter deck; the sullen demeanour of the turbaned Moor, who sits crosslegged at a shady corner ... ; the filthy, slip-shod, abject Jew, who wallows anywhere in the dirt, selling slippers or oranges, or with a bag over his head or a rope round his neck, ready to serve officers, merchants, sailors, or Moors, as a beast of burden ..."

Gibraltar was an unhealthy place to live due to its poor sanitation and living conditions. It was repeatedly ravaged by epidemics of yellow fever and cholera, which killed thousands of the inhabitants and members of the garrison. An epidemic in the second half of 1804 killed more than a third of the entire population, civilian and military. Lord Nelson wrote the following March that he hoped that Gibraltar "will escape the dreadful scourge of last autumn, and I hope that General Fox has burnt down all the small houses at the back of the Town; and perhaps if half the Town went with them, it would be better for the Rock."

During the wars against Napoleonic France, Gibraltar served first as a Royal Navy base from which blockades of the ports of Cadiz, Cartagena and Toulon were mounted, then as a gateway for British forces and supplies in the Peninsular War between 1807 and 1814. In July 1801 a French and Spanish naval force fought the two Battles of Algeciras off Gibraltar, which ended in disaster for the Spanish when two of their largest warships each mistook the other for the enemy, engaged each other, collided, caught fire and exploded, killing nearly 2,000 Spanish sailors. Two years later Gibraltar served as a base for Lord Nelson in his efforts to bring the French Admiral Pierre-Charles Villeneuve to battle, which culminated in the Battle of Trafalgar in which Nelson was killed and Villeneuve captured. Nelson sailed to Gibraltar in June 1803 to launch the Trafalgar Campaign and oversee the blockades against France and Spain, though he spent little time ashore. On 28 October 1805, a week after the Battle of Trafalgar, the badly damaged HMS Victory returned to Gibraltar with Nelson's body aboard; Admiral Collingwood's dispatch to General Fox, announcing the victory and Nelson's death, was printed in the pages of the Gibraltar Chronicle. It thus became the first newspaper in the world to report the victory at Trafalgar, two weeks ahead of The Times.

In the years after Trafalgar, Gibraltar became a major supply base for supporting the Spanish uprising against Napoleon. The French invasion of Spain in 1808 prompted Gibraltar's British garrison to cross the border and destroy the ring of Spanish fortresses around the bay, as well as the old Spanish fortified lines on the isthmus, to deny the French the ability to besiege Gibraltar or control the bay from shore batteries. French forces reached as far as San Roque, just north of Gibraltar, but did not attempt to target Gibraltar itself as they believed that it was impregnable. The French besieged Tarifa, further down the coast, in 1811–12 but gave up after a month. Gibraltar faced no further military threat for a century.

After peace returned, Gibraltar underwent major changes during the reformist governorship of General Sir George Don, who took up his position in 1814. The damage caused by the Great Siege had long since been repaired, but Gibraltar was still essentially a medieval town in its layout and narrow streets. A lack of proper drainage had been a major contributing factor in the epidemics that had frequently ravaged the fortress. Don implemented improved sanitation and drainage as well as introducing street lighting, rebuilding St Bernard's Hospital to serve the civilian population and initiating the construction of the Cathedral of the Holy Trinity to serve Gibraltar's Protestant civilians. For the first time, civilians began to have a say in the running of Gibraltar. An Exchange and Commercial Library was founded in 1817, with the Exchange Committee initially focused on furthering the interests of merchants based in the fortress. The Committee evolved into a local civilian voice in government, although it had no real powers. A City Council was established in 1821, and in 1830 Gibraltar became a Crown colony. In the same year, the Gibraltar Police Force was established, modelled on London's pioneering Metropolitan Police Service, and a Supreme Court was set up to try civil, criminal and mixed cases.

The economic importance of Gibraltar changed following the invention of steamships; the first one to reach Gibraltar's harbour arrived there in 1823. The advent of steamships caused a major shift in trade patterns in the Mediterranean. Transshipment, which had previously been Gibraltar's principal economic mainstay, was largely replaced by the much less lucrative work of servicing visiting steamships through coaling, victualling and ferrying of goods. Although Gibraltar became a key coaling station where British steamships refuelled on the way to Alexandria or Cape Horn, the economic changes resulted in a prolonged depression that lasted until near the end of the century. The demand for labour for coaling was such that Gibraltar instituted the practice of relying on large numbers of imported Spanish workers. A shanty town sprang up on the site of the old Spanish fortifications just across the border, which became the workers' town of La Línea de la Concepción. The poor economy meant that Gibraltar's population barely changed between 1830 and 1880, but it was still relatively more prosperous than the severely impoverished south of Spain. As a consequence, La Línea's population doubled over the same period and then doubled again in the following 20 years. Visiting Gibraltar in the mid-19th century, the English writer Richard Ford wrote in his Handbook for Travellers in Spain that "the differences of nations and costumes are very curious: a motley masquerade is held in this halfway house between Europe, Asia, and Africa, where every man appears in his own dress and speaks his own language. Civilization and barbarism clash here indeed ... or the Rock, like Algeria, is a refuge for destitute scamps, and is the asylum for people of all nations who expatriate themselves for their country's good." He described the town's Main Street as "the antithesis of a Spanish town", lined with "innumerable pot–houses" which made it a "den of gin and intemperance; every thing and body is in motion; there is no quiet, no repose; all is hurry and scurry, for time is money and Mammon is the god of Gib, as the name is vulgarized ... The entire commerce of the Peninsula seems condensed into this microcosmus, where all creeds and nations meet, and most of them adepts at the one grand game of beggar my neighbour."

Relations with Spain during the 19th century were generally amicable. Regular British soldiers were forbidden to cross the border but officers could cross freely into Spain, as could the inhabitants of Gibraltar, some of whom had second houses in the town of San Roque about six miles away. The garrison introduced the very British activity of fox hunting in the form of the Royal Calpe Hunt, started in 1812, which saw British officers and local Spanish gentry pursuing foxes across the Campo de Gibraltar. A major bone of contention during this period was the issue of smuggling across the border. The problem arose after Spain imposed tariffs on foreign manufactured goods in a bid to protect Spain's own fledgling industrial enterprises. Tobacco was also heavily taxed, providing one of the government's principal sources of revenue. The inevitable result was that Gibraltar, where cheap tobacco and goods were readily available, became a centre of intensive smuggling activity. The depressed state of the economy caused smuggling to become a mainstay of Gibraltar's trade; the mid-19th century Irish traveller Martin Haverty described Gibraltar as "the grand smuggling depot for Spain". General Sir Robert Gardiner, who served as Governor between 1848 and 1855, described the daily scene in a letter to British Prime Minister Lord Palmerston:

"From the first early opening of the gates there is to be seen a stream of Spanish men, women and children, horses and a few caleches, passing into the town where they remain moving about from shop to shop until about noon. The human beings enter the Garrison in their natural sizes, but quit it swathed and swelled out with our cotton manufactures, and padded with tobacco, while the carriages and beasts, which come light and springy into the place, quit it scarcely able to drag or bear their burdens. The Spanish authorities bear part in this traffic, by receiving a bribe from every individual passing the Lines, their persons and their purposes being thoroughly known to them. Some of these people take hardware goods, as well as cotton and tobacco, into Spain."

The problem was eventually reduced by imposing duties on imported goods, which made them much less attractive to smugglers and raised funds to make much-needed improvements to sanitation. Despite the improvements made earlier in the century, living conditions in Gibraltar were still dire. A Colonel Sayer, who was garrisoned at Gibraltar in the 1860s, described the town as "composed of small and crowded dwellings, ill ventilated, badly drained and crammed with human beings. Upwards of 15,000 persons are confined within a space covering a square mile." Although there were sewers, a lack of water made them virtually useless in summer and the poorer inhabitants were sometimes unable to afford enough water even to wash themselves. One doctor commented that "the open street is much more desirable than many of the lodgings of the lower orders of Gibraltar." The establishment of a Board of Sanitary Commissioners in 1865 and work on new drainage, sewerage and water supply systems prevented further major epidemics. A system of underground reservoirs capable of containing 5 million gallons (22.7 million litres) of water was constructed within the Rock of Gibraltar. Other municipal services arrived as well – a gas works in 1857, a telegraph link by 1870 and electricity by 1897. Gibraltar also developed a high-quality school system, with as many as 42 schools by 1860.

By the end of the 19th century, the "Gibraltarians" were given an official identity for the first time. It was only in the 1830s that Gibraltar-born residents began to outnumber foreign-born, but by 1891 nearly 75% of the population of 19,011 people were Gibraltar-born. The emergence of the Gibraltarians as a distinct group owed much to the pressure on housing in the territory and the need to control the numbers of the civilian population, as Gibraltar was still first and foremost a military fortress. Two Orders in Council of 1873 and 1885 stipulated that no child of alien parent could be born in Gibraltar, no foreigners could claim a right of residence and that only Gibraltar-born inhabitants were entitled to reside there; everyone else needed permits, unless they were employees of the British Crown. In addition to the 14,244 Gibraltarians, there were also 711 British people, 695 Maltese and 960 from other British dominions. There were 1,869 Spaniards (of whom 1,341 were female) with smaller numbers of Portuguese, Italians, French and Moroccans.

Gibraltar at war and peace
By the end of the 19th century and beginning of the 20th, Gibraltar's future as a British colony was in serious doubt. Its economic value was diminishing, as a new generation of steamships with a much longer range no longer needed to stop there to refuel en route to more distant ports. Its military value was also increasingly in question due to advances in military technology. New long-range guns firing high-explosive shells could easily reach Gibraltar from across the bay or in the Spanish hinterland, while the development of torpedoes meant that ships at anchor in the bay were also vulnerable. The garrison could hold out for a long time, but if the Spanish coast was held by an enemy, Gibraltar could not be resupplied in the fashion that had saved it in the Great Siege 120 years earlier.

A Spanish proposal to swap Gibraltar for Ceuta on the other side of the Strait was considered but was eventually rejected. It was ultimately decided that Gibraltar's strategic position as a naval base outweighed its potential vulnerability from the landward side. From 1889, the Royal Navy was greatly expanded and both Gibraltar and Malta were equipped with new, torpedo-proof harbours and expanded, modernised dockyards. The works at Gibraltar were carried out by some 2,200 men at the huge cost of £5 million (£0 in 2013 prices). Under the reforming leadership of First Sea Lord Admiral John "Jacky" Fisher, Gibraltar became the base for the Atlantic Fleet. In the British public's imagination, Gibraltar was seen as "a symbol of British naval power [and] a symbol of the empire which has been built and, more than the British lion or even John Bull himself, has come to represent Britain's power and prestige across the world."

The value of the naval base was soon apparent when the First World War broke out in August 1914. Only a few minutes after the declaration of war went into effect at midnight on 3/4 August, a German liner was captured by a torpedo boat from Gibraltar, followed by three more enemy ships the following day. Although Gibraltar was well away from the main battlefields of the war – Spain remained neutral and the Mediterranean was not contested as it was in the Second World War – it played an important role in the Allied fight against the German U-boat campaign. The naval base was heavily used by Allied warships for resupplying and repairs. The Bay of Gibraltar was also used as a forming-up point for Allied convoys, while German U-boats stalked the Strait looking for targets. On two occasions, Gibraltar's guns unsuccessfully fired on two U-boats travelling through the Strait. Anti-submarine warfare was in its infancy and it proved impossible to prevent U-boats operating through the Strait. Only two days before the end of the war, on 9 November 1918, SM UB-50 torpedoed and sank the British battleship HMS Britannia off Cape Trafalgar to the west of Gibraltar.

The restoration of peace inevitably meant a reduction in military expenditure, but this was more than offset by a large increase in liner and cruise ship traffic to Gibraltar. British liners travelling to and from India and South Africa customarily stopped there, as did French, Italian and Greek liners travelling to and from America. Oil bunkering became a major industry alongside coaling. An airfield was established in 1933 on the isthmus linking Gibraltar to Spain. Civil society was reformed as well; in 1921 an Executive Council and an elected City Council were established to advise the governor, in the first step towards self-government of the territory.

The outbreak of the Spanish Civil War in July 1936 presented Gibraltar with major security concerns, as it was initially on the front lines of the conflict. The ultimately successful rebellion led by General Francisco Franco broke out across the Strait in Morocco, and the Spanish Republican government sought on several occasions to regain control of the Nationalist-controlled area around Algeciras. Although Gibraltar was not directly affected by the fighting, the war caused significant disruption. An undetermined number of Spanish refugees, perhaps as many as 10,000 persons, fled to Gibraltar, resulting in severe overcrowding. A Non-Intervention Patrol was mounted by the Royal Navy, operating from Gibraltar, to prevent foreign military aid reaching the belligerents in Spain. In May 1937, one of the ships involved in the patrol, the destroyer HMS Hunter, hit a Nationalist mine and had to be towed back to Gibraltar with eight of her crew dead. The Spanish Civil War had a deep impact on Gibraltarian society. On one hand, the British authorities, the Anglican and Catholic churches and the Gibraltarian moneyed class supported the Nationalists in the War, while the working class sided with the Republicans. With Europe sliding towards a general war, the British Government decided to strengthen Gibraltar's defences and upgrade the naval base to accommodate the latest generation of battleships and aircraft carriers. A Gibraltar Defence Force (now the Royal Gibraltar Regiment) was established in March 1939 to assist with home defence.

Second World War
The outbreak of the Second World War in September 1939 did not initially cause much disruption in Gibraltar, as Spain and Italy were neutral at the time. The situation changed drastically after April 1940 when Germany invaded France, with Italy joining the invasion in June 1940. The British Government feared that Spain would also enter the war and it was decided to evacuate the entire civilian population of Gibraltar in May 1940. Most went to the United Kingdom and others to Madeira and Jamaica, while some made their own way to Tangier and Spain. An intensive programme of tunnelling and refortification was undertaken; over 30 miles of tunnels were dug in the Rock, and anti-aircraft batteries were installed in numerous locations in the territory. A new and powerful naval group called Force H was established at Gibraltar to control the entrance to the Mediterranean and support Allied forces in North Africa, the Mediterranean and the Atlantic. The airfield, which was now designated RAF North Front, was also extended using spoil from the tunnelling works so that it could accommodate bomber aircraft being ferried to North Africa. The garrison was greatly expanded, reaching a peak of 17,000 in 1943 with another 20,000 sailors and airmen accommodated in Gibraltar at the same time.

During the Battle of the Atlantic, Gibraltar played a key role. The Ocean Convoy System adopted by Britain after the fall of France in June 1940 ran on two routes – an east–west route between the UK and North America, and a north–south route between the UK, Gibraltar and Freetown in British-ruled Sierra Leone. Even before the war, Gibraltar had been designated as one of the main assembly points for convoys heading inbound to Europe. From late 1942, Gibraltar was the destination of the Central Atlantic convoy route between the United States and the Mediterranean in support of Allied operations in North Africa, Sicily, Italy and elsewhere in the region. A huge number of Allied troops and ships travelled this route; between November 1942 and August 1945, 11,119 ships travelled in 189 convoys between Gibraltar and the United States and vice-versa, and between December 1942 and March 1945, 536,134 troops were transported from the United States to Gibraltar.

Gibraltar was directly attacked, both overtly and covertly, on several occasions during the war. Vichy French aircraft carried out bombing attacks in 1940 and there were sporadic raids from Italian and German long-range aircraft, though the damage caused was not significant. Franco's position changed subtly from one of neutrality to "non-belligerence", which in practice meant allowing the Axis powers to operate covertly against Gibraltar from Spanish territory. Despite Franco's willingness to overlook German and Italian activities in and around the Bay of Gibraltar, he decided not to join Hitler's planned Operation Felix to seize the territory. A major factor influencing his decision was the vulnerability of Spain's food supplies, as the country was unable to feed itself after the destruction of the Civil War. It relied on grain imports from the Americas, which would certainly have been cut off had Franco gone to war with the Allies. Hitler eventually abandoned Felix to pursue other priorities such as the invasions of Yugoslavia and the Soviet Union.

German and Italian spies kept a constant watch on Gibraltar and sought to carry out sabotage operations, sometimes successfully. The Italians repeatedly carried out raids on Gibraltar's harbour using human torpedoes and divers operating from the Spanish shore, damaging a number of merchant ships and sinking one. Three Spaniards being run as spies and saboteurs by the German Abwehr were caught in Gibraltar in 1942–43 and hanged. The threat to Gibraltar was greatly reduced after the collapse of Italy in September 1943.

Post-war Gibraltar
Although Gibraltar's civilian inhabitants had started to return as early as April 1944, the last evacuees did not arrive back home until as late as February 1951. The immediate problem after VJ Day was a lack of shipping, as all available vessels were needed to bring troops home, but the longer-term problem was a lack of civilian housing. The garrison was relocated to the southern end of the peninsula to free up space and military accommodation was temporarily reused to house the returning civilians. A programme to build housing projects was implemented, though progress was slow due to shortages of building materials. By 1969, over 2,500 flats had either been built or were under construction.

In the war's aftermath, Gibraltar took decisive steps towards implementing civilian self-governance over most issues of public policy. The Association for the Advancement of Civil Rights (AACR), led by Gibraltarian lawyer Joshua Hassan, won all of the seats in the first post-war City Council elections in 1945. Women were given the right to vote in 1947, and in 1950 a Legislative Council was established. A two-party system had emerged by 1955 with the creation of the Commonwealth Party as a rival to the AACR. That same year Hassan became the first Mayor of Gibraltar. The Governor still retained overall authority and could overrule the Legislative Council. This inevitably caused tension and controversy if the Governor and Legislative Council disagreed, but in 1964 the British Government agreed to confine the powers of the Governor to matters of defence, security and foreign relations. A new constitution was decided on in 1968 and promulgated in 1969, merging the City Council and Legislative Council into a single House of Assembly (known as the Gibraltar Parliament since 2006) with 15 elected members, two non-elected officials and a speaker. The old title of "Colony of Gibraltar" was dropped and the territory was renamed as the City of Gibraltar.

Gibraltar's post-war relationship with Spain was marred by an intensification of the long-running dispute over the territory's sovereignty. Although Spain had not attempted to use military force to regain Gibraltar since 1783, the question of sovereignty was still present. Disputes over smuggling and the sea frontier between Gibraltar and Spain had repeatedly caused diplomatic tensions during the 19th century. The neutral zone between Spain and Gibraltar had also been a cause of disputes during the 19th and 20th centuries. This originally had been an undemarcated strip of sand on the isthmus between the British and Spanish lines of fortifications, about 1 km wide – the distance of a cannon shot in 1704. Over the years, however, Britain took control of most of the neutral zone, much of which is now occupied by Gibraltar's airport. This expansion provoked repeated protests from Spain.

Spain's push to regain sovereignty over Gibraltar was fuelled by the decolonisation agenda of the United Nations, which had been initiated in 1946. In that year, Britain had listed Gibraltar among other "Overseas Dependent Territories" in conjunction with the drive towards decolonisation, but it was not appreciated at the time that Gibraltar was in a unique position; due to the terms of the Treaty of Utrecht, it could only be British or Spanish and could not gain independence. Franco's government calculated that Britain would be willing to give up an expensive possession that no longer had a great deal of military value, but this turned out to be a fundamental misjudgement. The British government followed a policy of allowing its colonies to become self-governing entities before giving them the option of independence. Almost all took it, choosing to become independent republics. That option was not available to Gibraltar under the terms of the Treaty of Utrecht, which required that if Britain ever relinquished control it was to be handed back to Spain. The Gibraltarians strongly opposed this and organised a referendum in September 1967 in which 12,138 voters opted to remain with Britain and only 44 supported union with Spain. Spain dismissed the outcome of the referendum, calling the city's inhabitants "pseudo-Gibraltarians" and stating that the "real" Gibraltarians were the descendants of the Spanish inhabitants who had resettled elsewhere in the region over 250 years earlier.

The dispute initially took the form of symbolic protests and a campaign by Spanish diplomats and the state-controlled media. From 1954, Spain imposed increasingly stringent restrictions on trade and the movements of vehicles and people across the border with Gibraltar. Further restrictions were imposed in 1964, and in 1966 the frontier was closed to vehicles. In 1969, after the passing of the Gibraltar Constitution Order, to which Spain strongly objected, the frontier was closed completely and Gibraltar's telecommunications links through Spain were cut.

The Spanish decision had major consequences not only for the political relationship between Spain and the United Kingdom, but for the people of Gibraltar, many of whom had relatives or homes in Spain. As one of the Gibraltarians that suffered the closure of the frontier explains:

"The saddest sight was seeing people behind the wire fences on both sides of the land frontier yelling at the top of their voices across the wide dividing space to enquire about the state of relatives, as telephone communications had been cut by the Spaniards. Local housewives with Spanish relatives in the Campo area kept their radios tuned to the nearby Spanish stations for news of family members who were gravely ill. In critical cases the parties concerned would rush to Spain via Tangiers but unfortunately sometimes the patient was dead and buried by the time they arrived. The Spanish authorities would not allow access across the land frontier even on compassionate grounds."

Franco's death in 1975 led to the beginnings of diplomatic movement between Britain and Spain on the Gibraltar issue, though not immediately. Spain applied to join the European Economic Community (EEC) and NATO, for which it needed British support. In 1980, talks between British and Spanish ministers led to the Lisbon Agreement, a statement on cooperation between the two countries which committed them to starting negotiations on Gibraltar's future and lifting the Spanish restrictions on communications with Gibraltar. Although Britain promised to "honour the freely and democratically expressed wishes of the people of Gibraltar", Prime Minister Margaret Thatcher indicated in the House of Commons that sovereignty would be on the table, in a change from the previous policy. However, the border was not reopened due to "technical issues" – code for unresolved issues between the two governments – and the agreement was strongly opposed by many Gibraltarians, who did not wish their sovereignty to be under discussion and objected to the lack of Gibraltarian representatives at the talks. The outbreak of the Falklands War in 1982 caused a further delay. Argentina carried out an unsuccessful sabotage operation, kept secret at the time, that was intended to sink a Royal Navy frigate in Gibraltar's harbour; the saboteurs were captured by the Spanish police in Algeciras before they could carry out their attack. A further agreement was reached in Brussels in 1984 which clarified the Lisbon Agreement and required that Britain allow Spaniards to live and work in Gibraltar, which they would have the right to do anyway as EEC citizens. The border was finally fully reopened on 4–5 February 1985.

Modern Gibraltar
After the border reopened, the British government reduced the military presence in Gibraltar by closing the naval dockyard. The RAF presence was also downgraded; although the airport officially remains an RAF base, military aircraft are no longer permanently stationed there. The British garrison, which had been present since 1704, was withdrawn in 1990 following defence cutbacks at the end of the Cold War. A number of military units continue to be stationed in Gibraltar under the auspices of British Forces Gibraltar; the garrison was replaced with locally-recruited units of the Royal Gibraltar Regiment, while a Royal Navy presence is continued through the Gibraltar Squadron, responsible for overseeing the security of Gibraltar's territorial waters. In March 1988 a British military operation against members of the Provisional IRA (PIRA) planning a car bomb attack in Gibraltar ended in controversy when the Special Air Service shot and killed all three PIRA members.

The military cutbacks inevitably had major implications for Gibraltar's economy, which had up to that point depended largely on defence expenditure. It prompted the territory's government to shift its economic orientation and place a much greater emphasis on encouraging tourism and establishing self-sufficiency. Tourism in Gibraltar was encouraged through refurbishing and pedestrianising key areas of the city, building a new passenger terminal to welcome cruise ship visitors and opening new marinas and leisure facilities. By 2011, Gibraltar was attracting over 10 million visitors a year compared to a population of 29,752, giving it one of the highest tourist-to-resident ratios in the world.

The government also encouraged the development of new industries such as financial services, duty-free shopping, casinos and Internet gambling. Branches of major British chains such as Marks & Spencer were opened in Gibraltar to encourage visits from British expatriates on the nearby Costa del Sol. To facilitate the territory's economic expansion, a major programme of land reclamation was carried out; a tenth of Gibraltar's present-day land area was reclaimed from the sea. These initiatives proved enormously successful. By 2007, Chief Minister Peter Caruana was able to boast that Gibraltar's economic success had made it "one of the most affluent communities in the entire world." As of 2013, Gibraltar is ranked as the second most prosperous territory within the European Union and the 18th most prosperous worldwide in terms of gross domestic product by purchasing power parity per capita (the United Kingdom, for comparison, is 33rd worldwide and Spain is 44th). Today, Gibraltar has one Big Four accounting firm office per 10,000 people, the second highest in the world after the British Virgin Islands, and a bank per 1,700 people, the fifth most banks per capita in the world.

Gibraltar's relationship with Spain continued to be a sensitive subject. By 2002, Britain and Spain had proposed an agreement to share sovereignty over Gibraltar. However, it was opposed by the government of Gibraltar, which put it to a referendum in November 2002. The agreement was rejected by 17,000 votes to 187 – a majority of 98.97%. Although both governments dismissed the outcome as having no legal weight, the outcome of the referendum caused the talks to stall and the British government accepted that it would be unrealistic to try to reach an agreement without the support of the people of Gibraltar.

The tercentenary of the capture of Gibraltar was celebrated in the territory in August 2004 but attracted criticism from some in Spain. In September 2006, tripartite talks between Spain, Gibraltar and the UK resulted in a deal (known as the Cordoba Agreement) to make it easier to cross the border and to improve transport and communications links between Spain and Gibraltar. Among the changes was an agreement to lift restrictions on Gibraltar's airport to enable airlines operating from Spain to land there and to facilitate use of the airport by Spanish residents. It did not address the vexed issue of sovereignty, but this time the government of Gibraltar supported it. A new Constitution Order was promulgated in the same year, which was approved by a majority of 60.24% in a referendum held in November 2006.