# Redirect an Old Domain to This Site

> Permanently redirects every request that arrives on your previous domain to the same address on your current domain, after a rebrand or domain move.

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

## Code

```php
// Old host names that should redirect to the current site.
$wpide_old_domains = array( 'old-example.com', 'www.old-example.com' );

add_action( 'template_redirect', function () use ( $wpide_old_domains ) {
    $request = isset( $_SERVER['HTTP_HOST'] ) ? strtolower( sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) ) : '';
    $request = preg_replace( '/:\d+$/', '', $request );
    $home    = strtolower( (string) wp_parse_url( home_url(), PHP_URL_HOST ) );

    if ( '' === $request || $request === $home || ! in_array( $request, array_map( 'strtolower', $wpide_old_domains ), true ) ) {
        return;
    }

    $uri = isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : '/';

    wp_safe_redirect( wp_parse_url( home_url(), PHP_URL_SCHEME ) . '://' . $home . $uri, 301 );
    exit;
}, 0 );
```

## Notes

The old domain must still point to this hosting account. List each old host name, including www versions.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Redirect an Old Domain to This Site" 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/
