Fix Double Slash in URLs Error in WordPress

James Parsons by James Parsons Updated Oct 30th, 2024 0 Comments

Some analytics and SEO suites will trigger errors if you're linking to pages that have two slashes. In Ahrefs, this shows up as a "Double slash in URL" error. Google says these are usually related to a bug in a website's code.

So, they're not good for your SEO and they should be fixed. Example, this should only have one slash:

  • domain.com/blog//your-post

WordPress should already redirect these automatically. But that doesn't change the fact that you're still linking to these erroneously:

  1. You're still linking to a 301 redirect (possibly on your own site) which is bad practice.
  2. Your link still contains an error; it has two slashes in it instead of 1.

I wrote some simple code to replace these errors on your entire site with one simple fix. Just plop this at the bottom of your theme's functions.php file:

// Cleans up double slashes in URLs within the main content area for better output formatting

function clean_double_slashes_in_content($content) {
    return preg_replace_callback(
        '#(https?://[^/\s]+)(/+)#i',
        function($matches) {
            return $matches[1] . '/';
        },
        $content
    );
}
add_filter('the_content', 'clean_double_slashes_in_content');

Now any links that have this error will be fixed!

A couple notes:

  • This excludes the double slash in http:// and https:// - those double slashes are obviously important and needed. So it won't remove those.
  • This only changes the issue on the front-end of your site; what your visitors and search engines will see. It doesn't actually make bulk updates to your database or update the link in the WordPress post editor. That means this fix is also completely reversible if you decide to remove this code later.

As long as you have this fixed enabled, you no longer have to worry about these hurting your SEO and you'll see those errors drop off.

Please let me know if this helped you! I'd also like to hear what you think about this fix and if you have any questions!

Related Code Snippets

Written by James Parsons

James Parsons is the founder and CEO of Content Powered, a premier content marketing agency that leverages nearly two decades of his experience in content marketing to drive business growth. Renowned for founding and scaling multi-million dollar eCommerce businesses through strategic content marketing, James has become a trusted voice in the industry, sharing his insights in Search Engine Watch, Search Engine Journal, Forbes, Entrepreneur, Inc, and other leading publications. His background encompasses key roles across various agencies, contributing to the content strategies of major brands like eBay and Expedia. James's expertise spans SEO, conversion rate optimization, and effective content strategies, making him a pivotal figure in the industry.