The Second Anglo–Afghan War (Pashto: د افغان-انګرېز دويمه جګړه) was fought between the United Kingdom and the Emirate of Afghanistan from 1878 to 1880, when the latter was ruled by Sher Ali Khan of the Barakzai dynasty, the son of former Emir Dost Mohammad Khan. This was the second time British India invaded Afghanistan. The war ended after the British emerged victorious against the Afghan rebels and the Afghans agreed to let the British attain all of their geopolitical objectives from the Treaty of Gandamak. Most of the British and Indian soldiers withdrew from Afghanistan. The Afghan tribes were permitted to maintain internal rule and local customs but they had to cede control of the area's foreign relations to the British, who, in turn, guaranteed the area's freedom from foreign military domination. This was aimed to thwart expansion by the Russian Empire into India.