JAKARTA, Indonesia — Indonesia’s Constitutional Court on Thursday narrowly rejected a petition asking it to criminalize all sex outside marriage, in a blow to religious conservatives who have been gaining influence in the secular, Muslim-majority country.

The court’s nine justices voted 5-4 to reject a suit filed in March 2016 by the Family Love Alliance, a group of conservative scholars. The group had asked the court to dramatically expand an existing law that bars married people from having sex with anyone but their spouse, arguing that it should apply to all sex between unmarried people.

Such a ban would also have effectively criminalized homosexuality, since Indonesia does not recognize same-sex marriage. Human rights advocates had feared an increase in the persecution of gay Indonesians, hundreds of whom have been arrested in a series of well-publicized raids of gay saunas and hotels over the past year or so. On Thursday, eight men arrested in the raids were sentenced to two years and six months in prison, and two more will be sentenced later.

The court’s decision came as a surprise to rights activists as well as conservatives, who packed a courtroom in Jakarta, the capital, to hear the ruling Thursday.