# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Redirects](https://wpide.com/library/category/redirects/)
- Tags: redirects, urls, seo
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/collapse-double-slashes-in-urls/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Fix URLs With Double Slashes" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
