ANKARA (Reuters) - Turkey's parliament has granted immunity from prosecution to members of the armed forces conducting counter-terrorism operations as security forces battle Kurdish militants in fighting that has killed thousands in the past year.

The law, passed late on Thursday, gives expansive powers to the military as it tries to stamp out an insurgency by the Kurdistan Workers Party (PKK) after last year's collapse of a two-year ceasefire.

Before becoming president in 2014, Tayyip Erdogan spent much of his rule as prime minister building up civilian oversight of the military. Critics say the new law undoes some of those reforms.

The legislation could make it harder to investigate allegations of rights abuses. The United Nations and human rights groups have raised concerns about such violations during the last year of operations that have been centered in densely populated cities. Hundreds of civilians have been killed, according to opposition parties.

Erdogan said 7,500 PKK fighters have been "neutralized" and almost 500 soldiers and police officers killed.

Meanwhile, six Turkish soldiers were killed in two attacks on Friday, the military said. Four soldiers were killed when an improvised explosive device detonated in Hakkari province, near the Iraqi border, it said on its website.

Rebels opened fire and killed two soldiers near the town of Derik in Mardin province, north of the Syrian border, it said.

Turkey, the United States and the European Union all consider the PKK a terrorist organization. It first took up arms against the Turkish state in 1984, and more than 40,000 people, mostly Kurds, have been killed since.

The new law requires permission from the military or political leadership for any prosecutions of soldiers. The law will be applied retroactively, thereby covering the operations undertaken over the past year.

Civil servants engaged in counter-terrorism activities will also be protected from prosecution, according to the law.

It expands the jurisdiction of military courts, where members of the security forces accused of criminal activities during their service will be prosecuted. Military commanders are now able to issue search warrants, it also mandates.

(Reporting by Gulsen Solaker in Ankara and Seyhmus Cakan in Diyarbakir; Writing by Ayla Jean Yackley; Editing by David Dolan)