Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

Code

// 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 add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.