Praise be to Allah.
Tahiyyat al-masjid (“greeting the mosque”) is Sunnah according to most of the scholars; some of the scholars stated that there was consensus on this point.
Abu Qatadah (may Allah be pleased with him) said:
“The Prophet (blessings and peace of Allah be upon him) said: “When one of you enters the mosque, let him not sit down until he has prayed two rak‘ahs.” (Narrated by al-Bukhari, 1167; Muslim, 714)
An-Nawawi (may Allah have mercy on him) said:
“The scholars are unanimously agreed that it is mustahabb to greet the mosque, and it is makruh to sit down without greeting it with no excuse, because of the hadith of Abu Qatadah which clearly states that that is not allowed.” (Al-Majmu‘, 3/544)
Al-Hafiz ibn Hajar (may Allah have mercy on him) said:
“The scholars unanimously agreed that the command in this case is a recommendation (as opposed to an obligation). Ibn Battal narrated from the literalists that it is obligatory, but Ibn Hazm stated that it is not obligatory.” (Fath al-Bari, 1/538, 539. See also al-Muhalla, 2/7)
It says in Fatawa al-Lajnah ad-Daimah (7/137):
“The Sunnah for the one who enters the mosque at any time is to pray tahiyyat al-masjid , because of the general meaning of the words of the Prophet (blessings and peace of Allah be upon him): “When one of you enters the mosque, let him not sit down until he has prayed two ra ‘ahs.” Sahih – agreed upon.”
Shaykh Ibn ‘Uthaymin (may Allah have mercy on him) said:
The view that tahiyyat al-masjid is obligatory is a strong view, but the more likely to be correct is the view that it is a confirmed Sunnah (Sunnah muakkadah). And Allah knows best.” (Majmu‘ al-Fatawa, 14/354)
And Allah knows best.