ARLINGTON, Va. — The former Republican National Committee chairman Ed Gillespie barely survived an anti-establishment scare to claim the Republican nomination for governor of Virginia on Tuesday, according to The Associated Press. He will face Lt. Gov. Ralph Northam in a November clash that may test how much of a burden President Trump is among moderate voters, who are deeply contemptuous of the president.

With all precincts reporting on Wednesday, Mr. Gillespie had a lead of about 4,300 votes, or about 1.2 percentage points, over Corey Stewart, the chairman of the Prince William County Board of Supervisors.

The unexpectedly narrow outcome illustrated Mr. Trump’s enduring appeal among conservatives.

Emulating the president’s incendiary style by railing against political correctness and vowing to protect the state’s Confederate monuments, Mr. Stewart defeated Mr. Gillespie in a number of rural counties. It was a deeply embarrassing night for Mr. Gillespie, who greatly outspent Mr. Stewart and entered the primary with significant name recognition after barely losing a challenge to Senator Mark Warner, a Democrat, three years ago.

Mr. Stewart embraced the president and assailed Mr. Gillespie, 55, in harsh terms, calling him “Establishment Ed,” in much the same way Mr. Trump gave derisive nicknames to his rivals in last year’s Republican primary. And Mr. Gillespie kept his distance from the president, rarely stating his name and, when pressed by Mr. Stewart, saying only that he had supported the party’s “ticket” in 2016.