Shirvanshahs to remain in power, under Safavid suzerainty, until 1538, when Safavid king Tahmasp I (r. 1524–1576) completely deposed them, and made the area into the Safavid province of Shirvan. The Sunni Ottomans briefly managed to occupy parts of present-day Azerbaijan as a result of the Ottoman–Safavid War of 1578–1590; by the early 17th century, they were ousted by Safavid Iranian ruler Abbas I (r. 1588–1629). In the wake of the demise of the Safavid Empire, Baku and its environs were briefly occupied by the Russians as a consequence of the Russo-Persian War of 1722–1723. Despite brief intermissions such as these by Safavid Iran's neighboring rivals, the land of what is today Azerbaijan remained under Iranian rule from the earliest advent of the Safavids up to the course of the 19th century. Modern history After the Safavids, the area was ruled by the Iranian Afsharid dynasty. After the death of Nader Shah (r. 1736–1747), many of his former subjects capitalized on the eruption of instability. Numerous self-ruling khanates with various forms of autonomy emerged in the area. The rulers of these khanates were directly related to the ruling dynasties of Iran and were vassals and subjects of the Iranian shah. The khanates exercised control over their affairs via international trade routes between Central Asia and the West. Thereafter, the area was under the successive rule of the Iranian Zands and Qajars. From the late 18th century, Imperial Russia switched to a more aggressive geo-political stance towards its two neighbors and rivals to the south, namely Iran and the Ottoman Empire. Russia now actively tried to gain possession of the Caucasus region which was, for the most part, in the hands of Iran. In 1804, the Russians invaded and sacked the Iranian town of Ganja, sparking the Russo-Persian War of 1804–1813. The militarily superior Russians ended the Russo-Persian War of 1804–1813 with a victory. Following Qajar Iran's loss in the 1804–1813 war, it was forced to concede suzerainty over most of the khanates, along with Georgia and Dagestan to the Russian Empire, per the Treaty of Gulistan. The area to the north of the river Aras, amongst which territory lies the contemporary Republic of Azerbaijan, was Iranian territory until Russia occupied it in the 19th century. About a decade later, in violation of the Gulistan treaty, the Russians invaded Iran's Erivan Khanate. This sparked the final bout of hostilities between the