When the Shirvanshah Shah dynasty was ended by the Safavid Shah Tahmasp I, Shirwan formed a province of the Safavids and was usually governed by a Khan, who is often called Beylerbey. Shirvan was taken by the Ottomans in 1578; however, Safavid rule was restored by 1607. In 1722, during the Russo-Persian War (1722–1723), the Khan of Quba, Husayn Ali, submitted to Peter the Great and was accepted as his dignitary. The Treaty of Saint Petersburg (1723) forced the Iranian king to recognise the Russian annexation. By the treaty between the Russian and Ottoman Empires in the year 1724, the coast of the territory of Baku, which was occupied by the Russians, was separated from the rest of Shirvan, which was left to the Ottomans. It was only when Nader Shah defeated the Ottomans (1735) that the Russians ceded back the coastal land and the other areas in the North and South Caucasus as conquered in 1722–1723 from Safavid Iran conform the Treaties of Resht and Ganja, and the area became part of the Afsharid Empire, by which century long Iranian rule was restored.