WordPress: How to Add a Trailing Slash to the Homepage's Canonical URL

Updated on

If you’re using the Yoast SEO plugin for WordPress, it will add canonical URL metatags on your WordPress pages. The problem is that if your WordPress site is in a subdirectory, the plugin might use the wrong canonical URL for the homepage.

Why WordPress Homepages Always Have a Trailing Slash

In most cases, for WordPress to be served from a subdirectory (like example.com/blog/), it has to sit in a physical subdirectory. The slash on the end of a URL indicates that it’s a physical directory. If you try to leave the trailing slash off, the server will 301 redirect you to the URL with a trailing slash.

The Yoast SEO plugin leaves off the trailing slash on the homepage canonical URL if your WP site sits in a directory and has certain permalink settings (which are unrelated to the root URL of the site). That means search engines will list the wrong URL in the SERPs.

How to Fix the Problem with PHP

If your WordPress site’s homepage canonical URL does not have a trailing slash, this code in the theme’s functions.php file should fix it:

function wpseo_canonical_home_url_fix( $canonical_url ) {
      // Add a trailing slash if it's missing in front page
     if ( is_front_page() ){
         return trailingslashit( $canonical_url );
     }
     return $canonical_url;
}
add_filter( 'wpseo_canonical', 'wpseo_canonical_home_url_fix' );

How to Inspect the Full Homepage URL

There is almost never a case where the homepage URL of your WordPress site won’t have a trailing slash on it. Sometimes browsers will hide the trailing slash, but it’s still there.

If you can’t see it in the browser’s address bar, copy the URL from the browser and paste it in a text editor to see the real URL. Or open the browser console (right-click and “Inspect Element” in Firefox), click on the “console” tab, and type this code to see the page’s real URL:

window.location.href

Here’s an example from Google’s homepage, revealing the trailing slash by using JavaScript.

window.location.href in Firefox

By “website”, I mean a site that sits in a folder on a web server, not a page that is virtually created without the presence of a physical folder.

If you still aren’t convinced, type google.com into a browser and look at the network tab in the web developer console. The raw headers will show that the request is made to / (the homepage) on google.com. Here are the relevant HTTP headers:

GET / HTTP/2
Host: www.google.com

To learn more about HTTP headers, check out the post about using curl for Web development.

Tagged with: SEO PHPWordPress

Feedback and Comments

What did you think about this page? Do you have any questions, or is there anything that could be improved? You can leave a comment after clicking on an icon below.