CAIRO — An Egyptian court on Tuesday nullified a government decision to transfer sovereignty of two strategic Red Sea islands to Saudi Arabia, in a surprising setback for President Abdel Fattah el-Sisi.

The ruling surprised even some of Mr. Sisi’s critics, who did not expect the judiciary to go against the government.

In April, Mr. Sisi transferred Tiran and Sanafir — arid and uninhabited islands at the mouth of the Gulf of Aqaba — to Saudi Arabia during a visit by the Saudi monarch, King Salman.

Saudi Arabia had placed the islands under Egyptian control in 1950, amid fears that Israel might seize them, and Mr. Sisi portrayed their return as a correction of a historical quirk rather than as a sale. Saudi Arabia has been a major financial supporter of Mr. Sisi’s since, as military chief, he led the ouster of his Islamist predecessor, Mohamed Morsi, in 2013.