# Wildcard Redirects for Moved Sections

> Redirects whole groups of old URLs with simple * patterns, for example everything under /old-blog/ to the same address under /blog/, without a redirect plugin.

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

## Code

```php
// Pattern => target. * matches anything; $1, $2 ... insert the matched text. Examples:
// '/old-blog/*'         => '/blog/$1',
// '/products/*/manual/' => '/docs/$1/',
$wpide_wildcard_redirects = array();

add_action( 'template_redirect', function () use ( $wpide_wildcard_redirects ) {
    $path = isset( $_SERVER['REQUEST_URI'] ) ? (string) wp_parse_url( wp_unslash( $_SERVER['REQUEST_URI'] ), PHP_URL_PATH ) : '';

    if ( '' === $path ) {
        return;
    }

    foreach ( $wpide_wildcard_redirects as $pattern => $target ) {
        $regex = '#^' . str_replace( '\*', '(.*?)', preg_quote( $pattern, '#' ) ) . '$#i';

        if ( ! preg_match( $regex, $path, $matches ) ) {
            continue;
        }

        $url = preg_replace_callback( '/\$(\d+)/', function ( $ref ) use ( $matches ) {
            return isset( $matches[ (int) $ref[1] ] ) ? $matches[ (int) $ref[1] ] : '';
        }, $target );

        $url       = preg_match( '#^https?://#i', $url ) ? $url : home_url( $url );
        $same_host = ! wp_parse_url( $url, PHP_URL_HOST ) || wp_parse_url( $url, PHP_URL_HOST ) === wp_parse_url( home_url(), PHP_URL_HOST );

        if ( $same_host && untrailingslashit( (string) wp_parse_url( $url, PHP_URL_PATH ) ) === untrailingslashit( $path ) ) {
            return;
        }

        wp_safe_redirect( $url, 301 );
        exit;
    }
}, 1 );
```

## Notes

The rule list is empty by default; add your own using the examples. Use * for any text and $1, $2 in the target for what each * matched. On a subdirectory install include the subdirectory in the patterns. Redirects to the same address are skipped, so a rule cannot loop.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Wildcard Redirects for Moved Sections" 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/
