The history of Shanghai spans over a thousand years and closely parallels the development of modern China. Originally a small agricultural village, Shanghai developed during the late Qing dynasty (1644–1912) as one of China's principal trading ports. Although nominally part of China, in practice foreign diplomats controlled the city under the policy of extraterritoriality. Since the reform and opening up of the early 1990s the city has burgeoned to become one of Asia's major financial centers and the world's busiest container port.

Early Era

The South Flank of the Yangtze Delta began to develop following the maximum Holocene marine transgression. As sediment accumulated and created new land, several parallel shell-rich sand ridges—locally known as Gangshen—were formed in present-day Jinshan and Fengxian districts in Shanghai. Ancient archaeological sites in Shanghai are mostly distributed along the western side of the Gangshen, with only a few occasionally found on the ridges themselves.

The earliest Neolithic settlements known in this area date to the Majiabang culture (50003300 BCE). This was overlapped by the Songze culture between around 3800–3300 BCE. In the lower stratum of the Songze excavation site in the modern-day Qingpu District, archaeologists found the prone skeleton of one of the Shanghai's earliest inhabitantsa 25-30-year-old male with an almost complete skull dated to the Majiabang era.

In the area east of the Gangshen up to Lihutang, the shoreline reached the Xinzhuang–Minhang–Nanqiao line by the 4th century, located about 10 km east of the Gangshen, and fully formed into land prior to the Tang Dynasty.

In the mid-8th century, the southeastern portion of Suzhou was detached to establish Huating County, which was subsequently governed under Suzhou and later Jiaxing. Prior to the 11th century, the Wusong River (historically known as the Song River) and its tributary, the Qinglong River, served as the main waterways, leading to the emergence of Qinglong Town as a major commercial port and naval base. By 1077, the commercial tax revenue collected here exceeded the total of all other taxes in the county combined.

However, by the Song dynasty, as continuous sedimentation narrowed the Wusong River, the course of the ancient Huangpu River shifted northward to discharge into the Wusong, gradually widening as it absorbed southern runoff. With Qinglong Town declining due to siltation, the outer port of Huating County relocated eastward to Shanghai Town along the developing Huangpu River.

Yuan, Ming, and Early–Mid Qing periods (1270s–1843) In 1277, due to its large population, Huating County was elevated to Songjiang Prefecture. In the early 1290s, five townships in eastern Huating were separated to establish Shanghai County under the jurisdiction of Songjiang Prefecture, with its administrative seat at Shanghai Town.

The soil and hydrological conditions along the eastern coast of Songjiang Prefecture were poorly suited for rice; the Yuan government thus excepted Shanghai County by levying wheat and beans for the autumn tax. Around the turn of the 14th century, cotton cultivation and advanced textile techniques—traditionally attributed to Huang Daopo following her return from Hainan—spread from Shanghai throughout the Yangzi Delta, establishing cotton as the region's main cash crop.

Following the excavation and integration of the Fanjiabang () channel east of Shanghai County in the early fifteenth century, the Huangpu replaced the Wusong as the primary waterway draining the region into the sea.

As Shanghai's cotton textile industry rapidly commercialized during the Ming dynasty, local demand outstripped regional supply. This led to a broader division of labor, with North China expanding raw cotton cultivation to supply the looms of the region.

In response to frequent wokou (Japanese pirate) raids along the coast, a city wall was constructed around the county seat of Shanghai in 1553.

Shanghai had its first contact with the Jesuits in 1603 when the Shanghai scholar-bureaucrat Xu Guangqi was baptized by Jesuit priest Matteo Ricci.

During the Qing dynasty, the local economy gradually recovered from the late Ming depression through the cotton industry and maritime shipping. Shanghai imported bean cakes from Shandong and Liaodong (Fengtian) to fertilize local fields while exporting cotton textiles and tea northward. At the same time, ships heading north used local mud and sand as ballast, which helped dredge the Huangpu River and improved anchorage conditions.

Following the Qing court's abolition of the maritime ban, customs offices were established in the four southeastern coastal provinces; the Jiangsu customs office was later relocated to Shanghai and subsequently placed under the supervision of the Su-Song Circuit Intendant stationed in Suzhou. In 1730, the Su-Song Circuit was transferred to Shanghai, from which time the city administered grain storage, water conservancy, defense, public security, and related affairs for the region that then included Suzhou, Songjiang, and Taicang.

By the mid-eighteenth century, Shanghai's growth had already broken through the original city walls, with commercial facilities such as wharves, warehouses, the customs house, and guild halls expanding rapidly between the city's East Gate and the banks of the Huangpu. The maritime transport sector also gave rise to local sand-junk merchants; by the early nineteenth century, these merchants had accumulated considerable capital through trade with the north and were increasingly merging with the gentry class.

Late Qing treaty port era (1843–1911)

During the late Qing dynasty, Shanghai's economy began to rival that of the traditionally larger market at Suzhou. In the 18th and early 19th centuries, exports of cotton and silk reached as far as Polynesia and Persia.Arnold Wright, Twentieth century impressions of Hongkong, Shanghai, and other treaty ports of China: their history, people, commerce, industries, and resources (1908). online

In 1832, the East India Company explored Shanghai and the Yangzi River as a potential trading center for tea, silk, and opium, but were rebuffed by local officials. Chinese attempts to prohibit the opium trade into China led to the First Opium War (1839–1842) with the United Kingdom; the Treaty of Nanjing, which concluded the war with a British victory, opened up five treaty ports in China to British merchants, including Shanghai. Similar treaties were quickly signed with other Western nations, and French, American and German merchants joined their British counterparts in establishing a presence in Shanghai, residing in sovereign concessions where they were not subject to Chinese laws. The British established their concession in 1845, the Americans in 1848 in Hongkou, north of Suzhou Creek, and the French set up their concession in 1849 west of the old Chinese city and south of the British Concession. In 1846, Peter Richards founded Richards' Hotel, the first western hotel in China. It would later become the Astor House. In 1850, the first English-language newspaper in Shanghai, the North China Herald, was launched.

The Taiping Rebellion was the largest of a number of widespread rebellions against the hugely unpopular Qing regime. In 1853, Shanghai was occupied by a triad offshoot of the rebels called the Small Swords Society. The fighting devastated much of the countryside but left the foreign settlements untouched.

In 1854 a group of Western businessmen met and formed the Shanghai Municipal Council to organise road repairs, refuse clearance and tax collection across the concessions. In 1863 the American concession (land fronting the Huangpu River to the north-east of Suzhou Creek) officially joined the British Settlement (stretching from Yang-ching-pang Creek to Suzhou Creek) to become the Shanghai International Settlement. Its waterfront became the internationally famous Bund. The Shanghai French Concession, to the west of the old town, remained independent and the Chinese retained control over the original walled city and the area surrounding the foreign enclaves. By the late-1860s Shanghai's official governing body had been practically transferred from the individual concessions to the Shanghai Municipal Council. The International Settlement was wholly foreign-controlled with the British holding the largest number of seats on the council and heading all the Municipal departments. No Chinese residing in the International Settlement were permitted to join the council until 1928.

Jardine's attempt to construct the Woosung "Road" railway in 1876China's firstproved initially successful until the death of a soldier on the tracks prompted the Chinese government to demand its nationalization. Upon the last payment in 1877, the local viceroy ordered the profitable railway dismantled and removed to Taiwan.Pong, David. "Confucian Patriotism and the Destruction of the Woosung Railway, 1877", pp. 647–676. Modern Asian Studies, Vol. VII, No. 4. Cambridge University Press, 1973. The telegraph that had been strung along the line of the railwayalso China's firstwas, however, allowed to remain in operation.

By the mid-1880s, the Shanghai Municipal Council had a practical monopoly over a large part of the city's services. It bought up all the local gas-suppliers, electricity producers and water-companies. In the early 20th century, it took control over all non-private rickshaws and the Settlement tramways. It also regulated opium sales and prostitution until their banning in 1918 and 1920 respectively.

The Treaty of Shimonoseki, which ended the First Sino-Japanese War, saw Japan emerge as an additional foreign power in Shanghai. Japan built the first factories in Shanghai, which were soon followed by other foreign powers. The Chinese defeat also spurred reformers within the Qing government to modernize more quickly, leading to the reestablishment of the Songhu Railway and its expansion into the Shanghai–Nanjing Railway.

Republic of China

The 1911 Xinhai Revolution, spurred in part by actions against the native-owned railways around Shanghai, led to the establishment of the Republic of China. During that time, Shanghai became the focal point of many activities that would eventually shape modern China.

In 1936, Shanghai was one of the largest cities in the world with 3 million inhabitants. Of those, only 35,000-50,000 were of European origin, but these controlled half the city under the unequal treaties that provided extraterritoriality until 1943.Gregory Bracken, "Treaty Ports in China: Their Genesis, Development, and Influence." Journal of Urban History (2019), Vol. 45 Issue 1, pp 168-176 Many White Russians fled to China after the 1917 Russian Revolution, trickling to Shanghai along the 1920s. The number of people with Russian origins was about 35,000 by the 1930s, well exceeding number of other people with European origin. These Shanghai Russians were sometimes poorly regarded by westerners, as their general poverty led them to take jobs considered unsuitable for Europeans, including prostitution.Newham, Fraser. "The White Russians of Shanghai". History Today, Dec 2005, Vol. 55, No. 12, pp. 20–27. However, among Russian emigration was layered, also including several well-to-do members. Russian artists dominated Shanghai's artistic life almost single-handedly. Many Jewish refugees from Nazi Germany arrived in the 1930s.David Kranzler, Japanese, Nazis & Jews: The Jewish Refugee Community of Shanghai, 1938-1945 (Yeshiva University Press, 1976).