The spread of Islamic State into the "ungoverned territory" of Libya helped sow the seeds for the atrocity which left up to 30 Britons dead at a Tunisian beach resort, Philip Hammond said.
The Foreign Secretary said the presence of IS, also known as Isil, in Libya posed a threat to neighbouring countries "which sadly we have seen realised".
Mr Hammond insisted it was not a mistake for the UK to be involved in the effort to oust Libyan dictator Muammar Gaddafi in 2011, even though the country has descended into chaos.
The gunman who killed 38 tourists in the massacre at Sousse, Seifeddine Rezgui, trained at a terrorist camp in Libya after crossing into the country in January, Tunisian security chief Rafik Chelli said.
Mr Hammond defended the UK's role in tackling IS, but highlighted its spread to Libya as a key development.
He told reporters at the Foreign Office: "I think the thing that has changed is the spread of Isil into the ungoverned territory of Libya, a neigbouring country to Tunisia.
"We have been dealing with Isil in Syria and Iraq, we have a significant military operation in Iraq where we are delivering the second largest number of air strikes against Isil targets. But as Isil has spread across Libya in this ungoverned space it has posed a threat not just to us but to the neighbouring countries, which sadly we have seen realised in this attack in Tunisia."
The UK was part of an international military coalition which supported the overthrow of Gaddafi and Mr Hammond stood by the decision to act.
"Colonel Gaddafi was a tyrant who was destroying Libya and threatening large numbers of the Libyan people. We intervened to prevent a massacre in Benghazi.
"But we should see this in the context it sits: this was a state that had had its institutions completely undermined and destroyed over 40 years of Gaddafi's dictatorship and it will take some time to rebuild a future Libyan state."
Mr Hammond hoped UN-brokered talks in Morocco between different factions "will lead to a government of national accord which can start to allow us to rebuild Libya".
Tunisian authorities believe Rezgui trained near Sabratha at the same time as the attackers who targeted tourists at the Bardo museum in Tunis in March.