Allah Almighty says: "And complete the Hajj and Umrah for Allah. But if you are prevented (on the way), then (offer) whatever sacrificial animal is easily available, and do not shave your heads until the sacrificial animal reaches its place. And whoever among you is ill or has an ailment of the head, then (he must give) a ransom of fasting, or charity, or a sacrifice." [Surah al-Baqarah: 196]
Imam al-Shafi'i (may Allah have mercy on him) said: "I have not heard any of the scholars of tafsir from whom I have preserved (knowledge) differ on the fact that this verse was revealed at al-Hudaybiyah, when the Prophet (peace and blessings be upon him) was prevented and the polytheists came between him (peace and blessings be upon him) and the House (of Allah); and that the Prophet (peace and blessings be upon him) offered his sacrifice at al-Hudaybiyah itself and shaved his head, and he (peace and blessings be upon him) returned having exited ihram; he (peace and blessings be upon him) did not reach the House, nor did his (peace and blessings be upon him) Companions, except Sayyiduna Uthman bin Affan (may Allah be pleased with him), who reached it alone."
Sayyiduna Ka'b bin Ujrah (may Allah be pleased with him) said that the Messenger of Allah (peace and blessings be upon him) saw Ka'b bin Ujrah (may Allah be pleased with him) while lice were falling from his head onto his face. He (peace and blessings be upon him) asked: "Are they troubling you?" Ka'b (may Allah be pleased with him) said: "Yes." So he (peace and blessings be upon him) ordered him to shave his head. The narrator said: They were at al-Hudaybiyah; it had not been made clear to them that they would exit ihram there, and they were hoping to enter Makkah. Then Allah Almighty revealed the ransom (fidyah), and the Messenger of Allah (peace and blessings be upon him) ordered him to give one faraq (sixteen ratls, or three sa's) of food to six poor people, or to fast for three days, or to sacrifice a goat.
Hadith Referenceالسنن الكبرى للبيهقي / كتاب الحج / 10074