So how to prevent the redirection?
On the front-end/public side of a WordPress site, that redirection is done by redirect_canonical()
which is hooked on template_redirect
, and if you really must disable that non-www to www or www to non-www redirection, you can try the following (add the code to your theme’s functions.php
file):
-
For disabling non-www to www redirection:
add_action( 'parse_request', 'wpse_395638_1' ); function wpse_395638_1( $wp ) { // If the current URL doesn't have any path and without the www prefix, e.g. // https://example.com or https://example.com/?foo=bar, then we completely // disable the canonical redirect by unhooking redirect_canonical(). if ( empty( $wp->request ) ) { $host = parse_url( home_url(), PHP_URL_HOST ); if ( 'www.' . $_SERVER['SERVER_NAME'] === $host ) { remove_action( 'template_redirect', 'redirect_canonical' ); } } } // This snippet doesn't disable canonical redirect, but the snippet ensures // that the redirect URL doesn't use the www prefix, unless the current URL // uses it. add_filter( 'redirect_canonical', 'wpse_395638_2', 10, 2 ); function wpse_395638_2( $redirect_url, $requested_url ) { $host = parse_url( $redirect_url, PHP_URL_HOST ); $host2 = parse_url( $requested_url, PHP_URL_HOST ); // If the current URL doesn't use www, we remove it from the redirect URL. if ( "www.$host2" === $host ) { $redirect_url = preg_replace( '#^http(s?)://www.#', 'http$1://', $redirect_url ); } return $redirect_url; }
-
For disabling www to non-www redirection:
add_action( 'parse_request', 'wpse_395638_1' ); function wpse_395638_1( $wp ) { // If the current URL doesn't have any path and with the www prefix, e.g. // https://www.example.com or https://www.example.com/?foo=bar, then we // completely disable the canonical redirect by unhooking redirect_canonical(). if ( empty( $wp->request ) ) { $host = parse_url( home_url(), PHP_URL_HOST ); if ( "www.$host" === $_SERVER['SERVER_NAME'] ) { remove_action( 'template_redirect', 'redirect_canonical' ); } } } // This snippet doesn't disable canonical redirect, but the snippet ensures // that the redirect URL uses the www prefix, unless the current URL doesn't // use it. add_filter( 'redirect_canonical', 'wpse_395638_2', 10, 2 ); function wpse_395638_2( $redirect_url, $requested_url ) { $host = parse_url( $redirect_url, PHP_URL_HOST ); $host2 = parse_url( $requested_url, PHP_URL_HOST ); // If the current URL uses www, we add it back to the redirect URL. if ( "www.$host" === $host2 ) { $redirect_url = preg_replace( '#^http(s?)://#', 'http$1://www.', $redirect_url ); } return $redirect_url; }
Additional Note: As I said in the comments, preventing the non-www to www (or vice-versa) redirection could lead to CORS errors due to mismatched origin hostname, e.g. example.com
!= www.example.com
, so just keep that in mind.