In 1838, a British expeditionary force marched into Afghanistan and arrested Dost Mohammad, sent him into exile in India and replaced him with the previous ruler, Shah Shuja. Following an uprising, the 1842 retreat from Kabul of British-Indian forces and the annihilation of Elphinstone's army, and the Battle of Kabul that led to its recapture, the British gave up on their attempts and allowed Dost Mohammad Khan as ruler and withdrew their military forces from Afghanistan. Dost Mohammad Khan would go on to expand the Afghan Realm greatly, with the capture of the Emirate of Herat in the Herat Campaign of 1862-63. Dost Mohammad died on 9 June 1863, a few months after his campaign to capture Herat. Dost Mohammad's successors would fight for the throne of Afghanistan, between Sher Ali Khan, Mohammad Afzal Khan, and Mohammad Azam Khan in the Afghan Civil War (1863-1869). Sher Ali would win this civil war and would go on to rule the realm until In 1878, the British had returned in the Second Anglo-Afghan War which was fought over perceived Russian influence in the region, Abdur Rahman Khan replaced Ayub Khan who had succeeded Sher Ali Khan after his death in 1879. Britain would gain control of Afghanistan's foreign relations as part of the Treaty of Gandamak of 1879, making it an official British Protected State. In 1893, Amir Abdur Rahman signed an agreement in which the ethnic Pashtun and Baloch territories were divided by the Durand Line, which forms the modern-day border between Pakistan and Afghanistan. Shia-dominated Hazarajat and pagan Kafiristan remained politically independent until being conquered by Abdur Rahman Khan in 1891–1896. He was known as the "Iron Amir" for his features and his ruthless methods against tribes. The ''Iron Amir'' viewed railway and telegraph lines coming from the Russian and British as "trojan horses" and therefore prevented railway development in Afghanistan. He died in 1901, succeeded by his son, Habibullah Khan.