‘Aishah reports that the Prophet sallallahu alehi wasallam said: “Allah cursed the Jews and Christians [because] they took the graves of their prophets as mosques.” This is related by al-Bukhari, Muslim, Ahmad, and an-Nasa’i.
Ahmad and Muslim record from Abu Marthad al-Ghanawi that the Prophet sallallahu alehi wasallam said: “Do not pray facing a grave and do not sit on one.” They also record that Jundub ibn ‘Abdullah al-Bajali heard the Prophet say, five days before he died: “The people before you took graves as mosques. I prohibit this to you.”
‘Aishah reports that Umm Salamah mentioned the churches she saw in Abyssinia and the pictures they contained to the Messenger of Allah. The Prophet said to her: “These are the people who, when a pious servant or pious man among them dies, build a mosque [place of worship] upon their graves and put those pictures in it. They are the worst of the whole creation in the sight of Allah.” This is related by al-Bukhari, Muslim, and an-Nasa’i.
The Prophet is also reported to have said: “Allah curses those who visit the graves and take them as mosques and light lamps over them.” Many scholars take this prohibition to be one of dislike, regardless of whether the grave is in front of the imam or behind him. According to the zahiri school, this prohibition is one of complete forbiddance and as such, prayer at a grave site is not valid. According to the Hanbali school, this applies only if there are three graves or more. If there is only one or two graves, then the prayer is valid although disliked if one prays facing a grave, otherwise it is not disliked.