UN High Commissioner for Refugees Filippo Grandi and International Organization for Migration director Antonio Vitorino asked in a joint statement "that 5,600 refugees and migrants currently held in centres across Libya be freed in an orderly manner and their protection guaranteed."
Failing that, they should be "evacuated to other countries from where accelerated resettlement is needed," their statement said.
On July 3, more than 50 refugees and migrants were killed during an airstrike on the Tajoura detention centre in eastern Tripoli, the statement noted.
After insisting that "countries must step forward with more evacuation and resettlement places," it added that resources were also needed to allow any migrants who wished to return home to be able to do so.
According to UN figures, around 50,000 refugees and asylum seekers now live in Libya, along with 800,000 migrants.
The statement insisted that migrant rescue ships operated by non-governmental organisations "must not be penalised for saving lives at sea.
"Commercial vessels must not be directed to bring rescued passengers back to Libya," either, it added.
In late June, Italian authorities on the island of Lampedusa seized a rescue ship belonging to German aid group Sea-Watch which had forced its way into port with dozens of rescued migrants on board and arrested its captain, Carola Rackete.
She was subsequently freed on bail, but still faces charges of helping people smugglers and resisting the authorities after forcing her way past Italian customs vessels.