Redirect to the www or Non-www Version of Your Domain
Sends visitors who arrive on the other version of your domain (with or without www) to the one set as your Site Address, so search engines see a single site.
Opens WPIDE on
Code
add_action( 'template_redirect', function () {
$home_host = strtolower( (string) wp_parse_url( home_url(), PHP_URL_HOST ) );
$request = isset( $_SERVER['HTTP_HOST'] ) ? strtolower( sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) ) : '';
$request = preg_replace( '/:\d+$/', '', $request );
if ( '' === $request || $request === $home_host ) {
return;
}
$bare_home = preg_replace( '/^www\./', '', $home_host );
$bare_request = preg_replace( '/^www\./', '', $request );
if ( $bare_home !== $bare_request ) {
return;
}
$scheme = wp_parse_url( home_url(), PHP_URL_SCHEME );
$uri = isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : '/';
wp_safe_redirect( $scheme . '://' . $home_host . $uri, 301 );
exit;
}, 0 );
Notes
Your host must point both versions to this site. A redirect at the server or DNS level is faster when available.
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.