A court has jailed two teachers in Bagerhat for making derogatory comments about Islam, invoking a rare law from the British colonial era that makes insulting any religion a crime.

The case began when students at the district's Hijla High School complained that the assistant teacher of a science class last Sunday dismissed the Quran as the word of Allah and said there was no heaven, Magistrate Anwar Parvez told the Associated Press late Tuesday.

The students, aged 17 to 18, along with others from a nearby Islamic school became incensed when the high school's head teacher backed up his colleague. A mob including students, parents and villagers attacked the teachers with sticks, forcing them to lock themselves in a room until police intervened, Parvez said.

"The situation went out of control," Parvez said, adding the mob "wanted to take law in their hands."

The magistrate of the quick-ruling court said the assistant teacher pleaded guilty to publicly insulting religion, and the two were sentenced to six months behind bars.

The law against insulting religion, imposed when Britain ruled the Indian subcontinent, is rarely used and aimed at preventing communal clashes and inciting violence.

Bangladesh has been roiled by an ongoing wave of deadly attacks on atheist writers, religious minorities and activists over the last two years.

On Monday night, a gang of young men stabbed two men to death in Dhaka, including the editor of a gay rights magazine who also worked for the US Agency for International Development.

It was the fifth such killing this year, after nine were cut down in 2015. International governments including the United States and aid groups have implored the Bangladeshi government to do more to safeguard free speech and protect members of civil society.