Intense fighting in Tripoli, including near the British embassy compound, already saw many staff evacuated last week but now the FCO will suspend its consulate once it has assisted the departure of British nationals.
In the last few days, sporadic fighting between rival militias has spread northwards in Tripoli.
Many of the consular staff were evacuated last Monday but the ambassador and core staff remained, although they will now also return to the UK.
A spokesman for the FCO said: "The protection of our staff is paramount, and we assess that the current environment in Tripoli does not allow us to operate safely. We have therefore decided temporarily to relocate UK-based staff from the country."
The embassy is arranging an assisted departure for British nationals, but will not be able to offer consular assistance after August 4.
There are believed to be between 100 and 300 Britons in the north African country.
"The UK Government has changed its travel advice to reflect the ongoing security situation. We advise against all travel to Libya and urge British nationals in Libya to leave through commercially available means," said an FCO spokesman.
The British embassy closure came as fire yesterday tore through Tripoli's main fuel depot after rockets fired by one of Libya's militias struck and ignited a tank, the National Oil company (NOC) said.
Black plumes of smoke rose over the fuel tanks, which store oil for use in the capital and are located near Tripoli's international airport.
Firefighters deployed to tackle the blaze were forced back by the fighting, NOC spokesman Mohamed al-Harari said.
Since the overthrow in 2011 of Colonel Muammar al-Gaddafi by rebels supported by British and French air strikes, the north African country has descended into a state of lawlessness as rival militias struggle for power and wealth.