The idea is to give it to uninfected men who are having unprotected sex with other men.

It is currently used in the US, Canada, Australia and France to help protect the most at-risk gay men.

The ruling was a victory for the National Aids Trust (NAT), which brought the case to court.

Deborah Gold, NAT chief executive, said: “This is fantastic news. It is vindication for the many people who were let down when NHS England absolved itself of responsibility for PrEP. The judgment has confirmed our view that it is perfectly lawful for NHS England to commission PrEP. Now NHS England must do just that."

She added: “Over 4,000 people are getting HIV every year in the UK – we desperately need further prevention options to add to condom use,” describing any delay to commissioning the treatment as “unethical and expensive”.

Campaigners have said that while the majority of gay men use condoms to prevent being infected with HIV, there is also an “ethical duty” to provide PrEP to those who do not.

Dr Michael Brady, medical director at the HIV/Aids charity Terrence Higgins Trust, welcomed the findings and described the drug as “a game-changer”.

Dr Jonathan Fielden, NHS England's director of specialised commissioning, said there would be an appeal against the conclusions.

He said: "In parallel with that we will set the ball rolling on consulting on PrEP so as to enable it to be assessed as part of the prioritisation round.

"Of course, this does not imply that PrEP - at what could be a cost of £10-20 million a year - would actually succeed as a candidate for funding when ranked against other interventions."

Dr Fielden said that if the drug was not found to be cost-effective, the pharmaceutical company behind it would be asked to submit improved prices.

Diane Abbott, the shadow health secretary,said: “This is a triumph – and a cost-effective one at that – in the fight against HIV, the prevalence of which is rising in the UK.

“It was wrong to even consider passing the buck on prescribing PrEP, to local public health budgets, which in 2016-17 alone have been cut by around £100 million.

“This would have meant that people who cannot afford to privately buy PrEP would be at a higher risk of contracting HIV than people who can.”

James Mildred, a spokesman from Christian organisation CARE raised fears that funding the drug would encourage promiscuity.

He said: "If this drug is ultimately made available on the NHS we think there is a danger it will end up promoting promiscuity and more hedonistic, but risky lifestyles.

'We would have very real concerns therefore that making PrEP more available will have unintended consequences.

Mr Mildred said that any reliance on the drug could also increase the risk of other sexually transmitted diseases.