How to force an HTML link to be absolute?

Arnaud picture Arnaud · Jun 17, 2013 · Viewed 34.5k times · Source

In my website, users can put an URL in their profile.

This URL can be http://www.google.com or www.google.com or google.com.

If I just insert in my PHP code <a href="$url">$url</a>, the link is not always absolute.

How can I force the a tag to be absolute ?

Answer

Marco Chiappetta picture Marco Chiappetta · Oct 4, 2016

If you prefix the URL with // it will be treated as an absolute one. For example:

<a href="//google.com">Google</a>.

Keep in mind this will use the same protocol the page is being served with (e.g. if your page's URL is https://path/to/page the resulting URL will be https://google.com).