Tunisia has closed its main border crossing with Libya after thousands of stranded Egyptian and foreign nationals, fleeing ongoing fighting and violence in Libya, tried to break through the passage, the Tunisian news agency said.

The unrest erupted on Friday when thousands of Egyptians, barred from entering Tunisia because they had no visa, held a protest then broke through part of a fence at the Ras Ajdir crossing, Tunisian security officials said.

The news comes as Tunisia urged its estimated 50,000 to 60,000 nationals living in Libya to leave "as soon as possible" because of violence that has raged there since mid-July.

"The ministry of foreign affairs urges Tunisians who find themselves in Libyan territory to return home as soon as possible," a ministry statement said.

The border clashes on Friday was the second incident at the border in as many days, as thousands of Libyans streamed into neighbouring Tunisia, along with foreign nationals.

The police responded by shooting in the air and firing tear gas. The officials spoke on condition of anonymity because they were not authorised to speak to the press.

Tunisia is the only escape route as fighting escalates in the Libyan capital, Tripoli, where rival armed groups have been battling for weeks for control over the airport.

An Associated Press reporter at the crossing said no one managed to make it to the other side and security forces used vehicles to physically block access.

After a Tunisian police officer was wounded by gunfire from the Libyan side of the border, authorities closed the crossing, the official Tunisian news agency TAP said.

A day earlier, two Egyptians were killed during a similar protest demanding to be let through. Tunisian officials say thousands of Libyans have been crossing the border each day the past week.

'Worst factional violence'

Libya is witnessing its worst factional violence since the downfall of the longtime leader Muammar Gaddafi in the 2011 civil war.

The Tripoli violence erupted in early July when armed groups originally from the western city of Misrata, which are allied to some politicians, carried out a surprise attack on militias from the western town of Zintan who control the airport.

Along with the fighting in Tripoli, which the health ministry said has killed 214 people and wounded more than 980 others, armed groups had overrun army bases in Libya's second largest city, Benghazi, and claimed control of the city over the last few days.

On Friday, a powerful explosion ripped through the main police headquarters in Benghazi, nearly flattening it, witnesses said. The blast shook nearby houses and echoed across the eastern city.

The intensity of the fighting prompted foreign diplomats to flee the country along with thousands of Libyans and foreign workers.

But with Tripoli International Airport closed by fighting, there are few options besides the Tunisian crossing.