A Philippine judge overruled his own government Wednesday and denied a U.S. request for custody of a Marine who is appealing a local rape conviction.

Judge Benjamin Pozon said he dismissed an agreement between the Philippine justice secretary and the U.S. ambassador for the transfer to the U.S. Embassy of Lance Cpl. Daniel Smith, 21.

Smith, who is from St. Louis, was sentenced on Dec. 4 to 40 years in jail for raping a 23-year-old Filipino woman. He was immediately sent to a Manila jail.

A provision of the 1998 Visiting Forces Agreement between the U.S. and the Philippines says that any U.S. servicemen accused of a crime shall be in U.S. custody until all judicial procedures are exhausted.

Pozon said the provision does not apply after a conviction, regardless of a pending appeal.

The ruling set the stage for a prolonged legal battle over interpretation of the Visiting Forces Agreement, which has allowed American troops to train Filipino soldiers in counterterrorism, particularly in the south, where Al Qaeda-linked militants are active.

Justice Secretary Raul Gonzalez told Radio DZBB that Pozon was wrong. Chief state prosecutor Jovencito Zuno said he was considering an appeal either at the appellate or the Supreme Court.

Click here to go to FOXNews.com's Asia Center.

Evalyn Ursua, a lawyer for the victim, welcomed the ruling, saying she admired the judge for his "courage and independence."

"We can just imagine the pressure coming from those in power for him to rule in favor of Smith and the U.S.," she said, adding her client was "very happy."

Smith has been locked up in the jail's records office, a room separate from other prisoners. Newspapers reported he has his own embassy guard at all times and food is brought for him from the embassy every day.

The case has stirred anti-American feelings in this former U.S. colony, where American troops held permanent bases until the Philippines closed them down in 1992.

Left-wing groups have staged regular protests outside the U.S. Embassy, claiming the American servicemen were getting special treatment.

The rape victim accused Smith of sexually assaulting her on Nov. 1, 2005 while three other Marines cheering him on.

Smith testified that the sex was consensual. The three other servicemen were acquitted.