Fix Double Slash in URLs Error in WordPress
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:
- You're still linking to a 301 redirect (possibly on your own site) which is bad practice.
- 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!
Comments