RIYADH, Saudi Arabia — As voters in Iran danced in the streets, celebrating the landslide re-election of a moderate as president, President Trump stood in front of a gathering of leaders from across the Muslim world and called on them to isolate a nation he said had “fueled the fires of sectarian conflict and terror.”

That nation was Iran.

In using the headline address of his first foreign trip as president to declare his commitment to Sunni Arab nations, Mr. Trump signaled a return to an American policy built on alliances with Arab autocrats, regardless of their human rights records or policies that sometimes undermine American interests.

At the same time, he rejected the path taken by his predecessor, Barack Obama. Mr. Obama engaged with Iran to reach a breakthrough nuclear accord, which Mr. Trump’s administration has acknowledged Iran is following.

Mr. Trump has presented the shift as a reinvestment in historical alliances with friendly nations in order to fight extremism and terrorism. But the juxtaposition of the election in Iran and the gathering in Saudi Arabia seemed to highlight a reality of the Middle East that presidents have long wrestled with: how to choose partners and seek American interests in a region torn by sectarian splits and competing agendas.

Iran and its proxies have effectively found themselves on the side of the United States in fighting the Islamic State in Iraq, while in Syria, they have been adversaries in their support for the rule of President Bashar al-Assad. Saudi Arabia has at times undermined the United States’ efforts to stabilize Afghanistan.

“We are picking one side in this geopolitical struggle, and there is very little room for gray,” said Frederic Wehrey, a senior fellow in the Middle East Program at the Carnegie Endowment for International Peace. “Sectarianism is a byproduct of this geopolitical rivalry, and we are inadvertently picking one side in this sectarian struggle.”

The two scenes — dancing in the streets in Tehran and Sunni leaders gathered in an opulent hall in Riyadh — also pointed to a complicating reality in the Middle East: There is often a disconnect between the leaders and their people.

In his remarks, Mr. Trump signaled his intention to end engagement with Iran, suggesting that it does not encourage change from inside the country.

But in Iran, many were pushing for change. Emboldened by the election results, crowds of Iranians in the capital, Tehran, demanded what they hope President Hassan Rouhani’s second term will bring: the release of opposition figures, more freedom of thought and fewer restrictions on daily life.

Mr. Rouhani’s supporters also expect his victory, with 57 percent of the vote, to bolster his outreach efforts to the West and the pursuit of more foreign investment to lift Iran’s ailing economy.

For those who voted for Mr. Rouhani, there was a feeling of tremendous relief that his challenger, the hard-line cleric Ebrahim Raisi, who criticized the nuclear deal with the United States and other Western powers, had lost.

“Bye-bye, Raisi,” the crowds chanted during the street gatherings.

“He faces a difficult task,” Fazel Meybodi, a Shiite Muslim cleric from the city of Qum, said of Mr. Rouhani. “Now he must provide more freedoms, break the hard-line monopoly on the state-run radio and television, and increase freedom of press.”

To achieve all that, Mr. Rouhani must persuade the hard-line-dominated judiciary and security forces to change their outlook, Mr. Meybodi said. “If he fails to deliver on at least 70 percent of those promises, his future is dark,” he added.

For decades, Saudi Arabia and Iran have competed for religious leadership and political influence across the Muslim world and beyond.

Saudi Arabia, the Sunni monarchy that controls Islam’s holiest sites, sees itself as the natural leader of the Muslim world and has used its lavish oil wealth to spread its austere version of the faith.

Iran, meanwhile, is the world’s largest Shiite nation and is led by clerics who seek to export the ideology of political Islam that brought them to power in 1979.

In his speech on Sunday, Mr. Trump, a guest of the Saudi monarch, spoke of a stronger alliance with mostly Sunni Muslim nations to fight terrorism and extremist ideology and to push back against Iran.

Video

President Trump spoke about a renewed effort to stamp out extremism during a centerpiece speech to Muslim leaders in Saudi Arabia on Sunday.CreditCreditStephen Crowley/The New York Times

“From Lebanon to Iraq to Yemen, Iran funds arms and trains terrorists, militias and other extremist groups that spread destruction and chaos across the region,” Mr. Trump told dozens of Muslim heads of state. “It is a government that speaks openly of mass murder, vowing the destruction of Israel, death to America, and ruin for many leaders and nations in this very room.”

That pointed to a departure from the policies of Mr. Obama, who pushed Persian Gulf countries like Saudi Arabia to move toward greater self-sufficiency in defense while pressing for the agreement to limit Iran’s nuclear program.

Proponents of that approach hoped that engagement with Iran would lead to greater moderation among its leaders, paving the way for its eventual reintegration into the world system.

But the nuclear deal angered gulf nations, who felt that it rewarded Iran for bad behavior while doing nothing to constrain its destabilizing activities in Arab countries.

For them, Mr. Trump’s return to America’s traditional allies was a great relief.

“The most important thing is that the relationship between Saudi Arabia and the United States is built on vision and numbers, not on slogans. They are building on shared interests,” said Ghassan Charbel, the editor in chief of Asharq Al-Awsat, a Saudi-owned newspaper. “It shows that the majority in the Arab and Islamic worlds will be close to the United States if it chooses to engage.”

The Arab nations hate Iran for using nonstate actors in Arab countries. Iran was fundamental in the creation of Hezbollah, the Lebanese militant group and political party that now has Lebanon’s strongest military force. More recently, Iran has sent military aid to help Mr. Assad fight rebels seeking his ouster, while also supporting militias in Iraq, Bahrain and Yemen.

But there is a gap between Iran’s older, ruling clerics and the ambitions of its people, as was made clear when Iranians came out in force to dance and protest in the streets this weekend, breaking Islamic rules and political taboos, in celebration of Mr. Rouhani’s re-election.

The election outcome was widely seen as evidence that Iran’s society has changed radically. Influenced by satellite television, cheaper international travel, the internet, waves of migration to big cities and access to higher education, most of Iranian society now adheres to middle-class values.

This collided with the anti-Western ideology and strict interpretation of Islam represented by Mr. Raisi and promoted by state organizations.

Some used the election’s success to criticize Mr. Trump’s visit to Saudi Arabia.

Hamidreza Taraghi, a hard-line analyst, said of Mr. Trump, “This man just wants to sell American weapons and use Iran as an excuse.”

In deepening the United States’ alliance with gulf countries, Mr. Trump is bringing it closer to nations that share few cultural values with the United States and have sometimes acted against its interests.

Saudi Arabia, for one, is a monarchy where citizens have few rights and the public practice of any religion other than Islam is banned. It has used its military and its oil wealth to protect the Sunni monarchy that rules over a Shiite majority in neighboring Bahrain and to prop up President Abdel Fattah el-Sisi of Egypt.

In adopting the gulf perspective on Iran, Mr. Trump could be assisting a strategy gulf leaders use when times get hard at home.

“It is feeding into the gulf narrative, where they project a lot of their insecurities about domestic politics outward and onto the Islamic Republic of Iran,” said Mr. Wehrey, the Carnegie fellow. “But is Iran the source of all evil in the region? No.”

Others questioned the value of working with autocrats to fight terrorism.

“The worldview that we are fighting against needs to be countered with liberal ideas, not Salafi ideas,” said Mokhtar Awad, a research fellow in the Program on Extremism at George Washington University, referring to Saudi Arabia’s conservative branch of Islam.