那么如何防止重定向呢?
在WordPress站点的前端/公共端,重定向由redirect_canonical()
它被钩住了template_redirect
, 如果你真的要禁用它non-www to www or www to non-www 重定向,您可以尝试以下操作(将代码添加到主题的functions.php
文件):
用于禁用non-www to www 重定向:
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;
}
用于禁用
www to non-www 重定向:
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;
}
其他注意事项:正如我在评论中所说,阻止非www到www(反之亦然)重定向可能会导致
CORS 源主机名不匹配导致的错误,例如。
example.com
!=
www.example.com
, 所以请记住这一点。