Ahmadinejad, who frequently enraged the West with his rhetoric during his eight years in office, wanted to challenge Rouhani's bid for a second term, but Khamenei warned him last year not to nominate himself.
Khamenei, who has the final say in Iran's clerical establishment, said in September that Ahmadinejad's candidacy could create division in the country and harm the nation.
However, the former leader's firebrand style could prove appealing for hardliners seeking a tough-talking candidate who can stand up to US President Donald Trump.
His candidacy could also expose the fissures inside Iranian politics that have lingered since his contested 2009 re-election, which brought widespread unrest.
It sparked large-scale protests and a sweeping crackdown in which thousands of people were detained and dozens killed.
Internationally, Ahmadinejad is better known for repeatedly questioning the scale of the Holocaust, predicting Israel's demise and expanding Iran's contested nuclear programme.
Last month, Iranian authorities arrested 12 social media activists who run reformist and pro-government discussion forums on the popular messaging app Telegram. Authorities released no information at the time of their arrests and the detainees have not appeared in open court.
It emerged yesterday that they were being held on "security and obscenity charges", the judiciary said yesterday.
Rouhani has criticised the arrests.
"I ordered the ministers of interior and intelligence to follow it up. Based on the intelligence minister's report, they haven't committed a crime," he told reporters.