All perfect praise be to Allaah, The Lord of the Worlds. I testify that there is none worthy of worship except Allaah, and that Muhammad, sallallaahu ‘alayhi wa sallam, is His Slave and Messenger.
Greeting the Masjid is a Sunnah Mu’akkadah (established tradition) for the one who enters the Masjid, having made Wudhoo’, and wanting to sit. Muslim narrated in his Saheeh from Abu Qataadah that the Messenger of Allaah, sallallaahu ‘alayhi wa sallam, said: "When one of you enters the Masjid, let him pray two Rak‘ahs before he sits." In another report: "He should not sit until he prays two Rak‘ahs."
This prayer is even established at the times when prayer is disliked, because it is a prayer with a specific purpose, which is not bound by the prohibition (of offering the prayer at those times) according to the most correct opinion of the scholars.
Greeting the Masjid is waived in the following situations:
• If the one entering is the Khateeb (speaker for the Jumu‘ah sermon), then the Sunnah is actually that he ascends the pulpit on the day of Jumu‘ah straight away, as soon as he enters, and he does not greet the Masjid, as this is what the Prophet, sallallaahu ‘alayhi wa sallam, did.
• If he is going to perform a different prayer, obligatory or not, since the purpose (of this ruling) is to occupy the place with prayer, and such would already happen, except for the Janaazah (funeral) prayer, due to the above-mentioned Hadeeth, "Let him pray two Rak‘ahs before he sits."
• If he enters the Masjid and finds the prayer is already established or he finds that the Mu’aththin has started the Iqaamah (declaration of the prayer's establishment), then it is only correct for him to join the Jamaa‘ah (congregation) and it is not legislated for him, at that time, to greet the Masjid, as the Prophet, sallallaahu ‘alayhi wa sallam, said: "If the prayer is commenced, then there shall be no prayer established except the obligatory one." [Muslim]
• If someone comes from outside of Makkah and performs the Tawaaf (encircling the Ka‘bah), since it would be included in the two Rak‘ahs performed for the Tawaaf. As for the one who is not coming from outside of Makkah, then it is correct that he prays two Rak‘ahs to greet the House (of Allaah) if he does not intend to perform the Tawaaf when he enters.
• If the one who enters the Masjid does so repeatedly, then it is sufficient that he greets the Masjid only once with his first entrance according to the Hanafis and the Maalikis; as for the Shaafi‘is and the apparent opinion of the Hanbalis, it is not waived but is rather recommended (to still greet the Masjid). This is the preferred opinion of Shaykh Al-Islaam Ibn Taymiyyah according to Ibn Muflih in Al-Furoo‘.