NEW DELHI—India's Supreme Court on Wednesday overturned a lower court's ruling that had decriminalized gay sex, a surprise setback for the gay-rights movement in this largely conservative country.

In 2009, the Delhi High Court ruled that a 19th-century provision in the nation's penal code that effectively banned gay sex shouldn't apply to consensual acts.

On Wednesday, the Supreme Court rejected that decision, saying the old law was still constitutionally valid and could only be changed or erased by Parliament, not the courts.

Rights groups say the law—known as Section 377 for its place in a 150-year-old Indian penal code—had been used for decades to harass homosexuals.

"We hold that Section 377 IPC does not suffer from the vice of unconstitutionality and the declaration made by the Division Bench of the High court is legally unsustainable," the two supreme-court judges who presided over the case said in their 98-page judgment, released late Wednesday.