By Ayman al-Warfalli and Feras Bosalum

BENGHAZI Libya (Reuters) - Nine Libyan soldiers were killed on Friday when Islamist fighters tried to storm the Benghazi city security headquarters in an attack authorities blamed on the militant group Ansar al-Sharia.

Libya's weak central government is struggling to control armed groups, militias and brigades of former rebels who helped oust long-time leader Muammar Gaddafi in the 2011 civil war and now refuse to disarm.

The dead were soldiers of a special forces unit, the Tripoli government said, for the first time openly blaming Ansar al-Sharia, which is listed as a terrorist organization by the United States.

"Armed brigades, including those called Ansar al-Sharia and other criminal groups, attacked the security headquarters in Benghazi with light and heavy weapons " a government statement said.

Special forces have often clashed with the heavily-armed militant group in Benghazi, Libya's second largest city, but the government with its nascent army had been reluctant to name it publicly for fear of provoking tensions.

EXPLOSIONS

Huge explosions could be heard during a firefight in the early morning that lasted more than an hour. Special forces later secured the headquarters, near the city center.

Helicopters and war planes were flying over Benghazi in the afternoon. Occasional gunfire and smaller explosions could still be heard during the day. As many as 15 more troops were also injured in the attack.

The bodies of two soldiers, kidnapped by militants during the attack, were found later bearing signs of torture, a medical source said.

Armed men also attacked the apartment of Benghazi's security chief Colonel Ramadan al-Wahishi. He was not hurt, a security official said.

Car bombings and assassinations of soldiers and police officers have become common in Benghazi, where a suicide bomber detonated an explosives-packed minibus outside a special forces camp on Tuesday, killing two people. Most countries have closed their consulates in the city and some foreign airlines have stopped flying there since the U.S. ambassador and three other Americans were killed in an Islamist militant attack in September 2012.

In December, a suicide bomber killed 13 outside an army camp on the outskirts of Benghazi, in the first suicide attack since the 2011 NATO-backed civil war that toppled Gaddafi.

Western diplomats worry that the violence will spill over to the capital Tripoli, where the security situation has also worsened. Kidnappings of foreign diplomats have been on the rise as well as nightly shootouts near the airport road.

Western and Arab allies are training Libya's fledgling armed forces but the military is still no match for the heavily armed former rebels and militias who often use the threat of force to make demands on the state.

(Reporting by Feras Bosalum and Ayman al-Warfalli; Writing by Ulf Laessing; Editing by Gareth Jones)