The second prosecutor on the case, Marine Capt. Connor McMahon, was not removed.

The Navy said it would obey the order. “Chief Petty Officer Edward Gallagher is entitled to a fair trial and the Navy is committed to upholding that principle,” said Brian O’Rourke, a Navy spokesman.

In response to the hearings, the judge on Thursday released Chief Gallagher from pretrial restriction, saying that giving him his freedom pending trial was “a remedy for prosecutors interfering with his Sixth Amendment right to counsel.”

The removal of the prosecutor was the latest twist in a case that has become politically charged, with a number of conservative lawmakers rallying around the chief and Mr. Trump signaling that he was considering pardoning him before trial. One member of Congress who had served in combat announced that like Chief Gallagher, he had taken photos of himself with dead bodies.

Chief Gallagher is accused of shooting two unarmed civilians — an old man and a school-age girl — from a sniper’s post during a 2017 deployment in Iraq, and stabbing a captive, wounded Islamic State fighter to death during the same deployment. He then took photos of himself with the captive’s body and texted them to another SEAL with the message, “Good story behind this, got him with my hunting knife.”

He has pleaded not guilty and denies all the charges. His defenders say he is being unfairly prosecuted for doing his job.

When he was released Thursday, his wife, Andrea Gallagher, told reporters outside the courtroom, “I feel like it’s a small victory on the way to the larger victory.”

The case has been dogged with leaks that have continued despite a judge’s gag order. Hoping to track down the source of the leaks, Commander Czaplak, working with Naval Criminal Investigative Service agents, sent emails to defense lawyers in May that had hidden monitoring software embedded in them, allowing prosectors to track who forwarded and who received the emails, court documents show.