According to Kipling in his autobiography Something of Myself, posthumously published in 1937, the poem was inspired by Dr. Leander Starr Jameson, who in 1895 led a raid by British forces against the Boers in South Africa, subsequently called the Jameson Raid. This defeat increased the tensions that ultimately led to the Second Boer War. The British press, however, portrayed Jameson as a hero in the middle of the disaster, and the actual defeat as a British victory. Jameson’s life — and the connection to the poem — is covered in the book The If Man.
If you can keep your head when all about you are losing theirs and blaming it on you; If you can trust yourself when all men doubt you, but make allowance for their doubting too; if you can wait and not be tired by waiting,or being lied about, don’t deal in lies, or being hated, don’t give way to hating, and yet don’t look too good, nor talk too wise; if you can dream — and not make dreams your master; if you can think — and not make thoughts your aim; if you can meet with Triumph and Disaster and treat those two impostors just the same.