TEHRAN — Riding a large turnout from Iran’s urban middle classes, President Hassan Rouhani won re-election in a landslide on Saturday, giving him a mandate to continue his quest to expand personal freedoms and open Iran’s ailing economy to global investors.

Perhaps as important, analysts say, the resounding victory should enable him to strengthen the position of the moderate and reformist faction as the country prepares for the end of the rule of the 78-year-old supreme leader, Ayatollah Ali Khamenei.

Of the 41 million votes cast, the Interior Ministry said, Mr. Rouhani won 23 million (or 57 percent), soundly defeating his chief opponent, Ebrahim Raisi, who received 15.7 million (38.5 percent). Iranian state television congratulated Mr. Rouhani on his victory.

Turnout was heavy, with more than 70 percent of Iran’s 56 million voters casting ballots.

Despite the healthy margin of victory, Mr. Rouhani, 68, will face considerable headwinds, both at home and abroad, as he embarks on his second term. He badly needs to demonstrate progress on overhauling the moribund economy.