ISTANBUL—Turkish President Recep Tayyip Erdogan attended Muslim prayers in this city’s iconic Hagia Sophia on Friday, two months immediately after he declared the building—a museum for the past 86 years—a mosque again in a controversial shift aimed at reviving nationalist sentiment.

Carrying a experience mask and flanked by his defense minister, Hulusi Akar, Mr. Erdogan sat in the middle of a entrance row dealing with the imam. Throngs of people gathered on the square and in the maze of cobbled streets encompassing Hagia Sophia to choose aspect in the prayers.