PHP echo URL for Canonical Tag & OG Tag


Technical SEO
Staff member
Save time on manually populating canonical tags and open-graph (OG) using a simple PHP snippet. This method will fetch the current URL loaded in the browser.

Replace your canonical and OG tag with the following:
<!-- canonical tag -->
<link rel="canonical" href="<?php $url="https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];echo $url;?>">

<!-- OG URL -->
<meta property="og:url" href="<?php $url="https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];echo $url;?>">

The output will look similar to this:

This method is SEO friendly, however, if you are canonicalising URLs (non-self-referencing). You will need to override the canonical to point at the new URL. This 'PHP echo URL for Canonical Tag & OG Tag' is meant for basic CMSes and semi-dynamic websites created in PHP. Popular CMSes such as WordPress and Drupal will dynamically create a canonical and possibly the OG URL.

I'm using this method, as I have bridged 3 CMSes.
Last edited: