Sonko was struck off Senegal's electoral roll after being sentenced in June to two years' imprisonment for morally corrupting a young person.
He has been at the center of a stand-off with the state that has lasted more than two years and sparked several episodes of deadly unrest.
In ordering Sonko's reinstatement, the judge in the capital Dakar confirmed a ruling in October by a court in Ziguinchor, the southern city where Sonko is mayor.
Last month, the West African nation's top court had disagreed with that regional court ruling.
But it nevertheless decided that Sonko's case should go back to the Dakar court.
Sonko now has until December 26 to present his candidacy for the February election and obtain the necessary sponsorships.
Jubilant supporters of Sonko — who is particularly popular among the under-20s that make up half the population — were in court on Thursday and shouted his name after the ruling.
One of his lawyers, Cire Cledor Ly, said the state could lodge an appeal with the Supreme Court but that would not stop Thursday's decision being implemented immediately.
"The electoral code is very clear. When the judge gives his decision, this decision must be immediately carried out," he said.
Sonko, 49, was convicted in absentia on June 1 of morally corrupting a young person and sentenced to two years in prison.
He condemned the trial as a plot to exclude him from the presidential election.
In late July, he was arrested on other charges including fomenting insurrection, criminally associating with a terrorist body and endangering state security.
He has periodically been on hunger strikes since then.
Forum