Quoting Deut. 16:16, he rules (Hilchot M’lachim 1:7), “It is permitted to settle everywhere except in Egypt”. But Egypt was precisely where he himself settled and where he became physican to the ruler.
Radbaz (Rabbi David ibn Zimra, 16th cent.), another famous figure in Egyptian Jewish history, explained that the ban applied to permanent settlement in Egypt; in his case he finally moved to the Land of Israel, which Maimonides would presumably have also wished to do had the opportunity arisen.
But Maimonides did live in Israel for a year, so why did he leave?
Rabbi Mordechai HaKohen, in an essay entitled “New Light on the Rambam in Egypt”, suggested that Maimonides believed that the imminent coming of the Mashi’ach was hindered by the fact that the Holy Land was in the hands of Christian Crusaders.
If the Christians could be ousted by the Muslims there was a greater chance that the Jews could regain their political independence in the Land. Hence good relations with the Muslim court in Egypt could assist the removal of the Christian regime, and Maimonides thought his residence in Egypt could secure Muslim support and thus help to bring the Mashi’ach.
There actually was a kind of Balfour Declaration issued by Saladin in 1188, but it did not result in the restoration of Jewish rule in the Holy Land: the king died soon afterwards and the Jews themselves were uninterested (Pinhas H. Peli, “An Egyptian Puzzle”, Jerusalem Post, 29 January, 1988).