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 Qataadah (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 rakahs.
Narrated by al-Bukhaari, 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 makrooh to sit down without greeting it with no excuse, because of the hadeeth of Abu Qataadah which clearly states that that is not allowed.
End quote from al-Majmoo, 3/544
Al-Haafiz ibn Hajar (may Allah have mercy on him) said: The scholars are unanimously agreed that the command in this case is a recommendation (as opposed to an obligation). Ibn Battaal narrated from the literalists that it is obligatory, but Ibn Hazm stated that it is not obligatory.
End quote from Fath al-Baari, 1/538, 539. See also al-Muhalla, 2/7
It says in Fataawa al-Lajnah ad-Daa'imah (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. Saheeh - agreed upon.
Shaykh Ibn Uthaymeen (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 mu'akkadah). And Allah knows best.
End quote from Majmoo al-Fataawa, 14/354
And Allah knows best.
Reproduced from Islam QA