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.
Opens WPIDE on
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
- 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.