The famous story says diehard was born on a Spanish battlefield in 1811. The phrase was in fact already about a century old, and its earliest record comes from the gallows.
Phrase Finder quotes a 1703 book, Psychologia, describing condemned men at Tyburn who "die hard, as they call it." Hanging there was slow, since the drop had not yet come into use. To die hard was simply to take a long time dying, struggling to the end.
The battlefield story is still true, and it is what made the phrase famous. On 16 May 1811, at the Battle of Albuera in the Peninsular War, the 57th (West Middlesex) Regiment of Foot stood against a French attack. Its commander, William Inglis, was hit by canister shot. He refused to be carried away and stayed by the regimental colours, calling on his men to die hard. Sources give his words differently. Wikipedia has "Die hard 57th, die hard!" and Military History has "Die Hard, the 57th, Die Hard!" Brewer's dictionary has "Die hard, my lads; die hard!"
The cost was enormous. The magazine Military History reports 428 casualties among the 647 officers and men present, about two thirds. Beresford, reporting on the battle, wrote that the 57th's dead lay "as they fought in the ranks, every wound in front." The 57th was known as the Die Hards from then on.
A century later the phrase moved into politics. In 1911 the Parliament Bill threatened to end the House of Lords' power to block laws. Some Conservative peers gave way to avoid the mass creation of new Liberal peers. Others refused to the end. Wikipedia notes that these were called Ditchers, or die-hards, and the bill passed the Lords by 131 votes to 114. Phrase Finder records the label for opponents of Irish Home Rule in 1912 as well. By 1922 a Conservative faction was calling itself "The Die-hards."
From there the word broadened to anyone who will not give up a cause. Phrase Finder points out that the 1988 film Die Hard plays on both the hero's toughness and how hard he is to kill.