Fix URLs With Double Slashes
Permanently redirects addresses that contain double slashes, such as /blog//my-post/, to the clean version, avoiding duplicate pages from broken links and badly built URLs.
Opens WPIDE on
Code
add_action( 'template_redirect', function () {
$uri = isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : '';
$pos = strpos( $uri, '?' );
$path = false === $pos ? $uri : substr( $uri, 0, $pos );
$query = false === $pos ? '' : substr( $uri, $pos );
if ( false === strpos( $path, '//' ) ) {
return;
}
// /blog//my-post/ and /blog///my-post/ become /blog/my-post/.
$home = wp_parse_url( home_url() );
$base = $home['scheme'] . '://' . $home['host'] . ( isset( $home['port'] ) ? ':' . $home['port'] : '' );
wp_safe_redirect( $base . preg_replace( '#/{2,}#', '/', $path ) . $query, 301 );
exit;
}, 1 );
Notes
The query string is kept as it is.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.