我想将www.example.com重定向到example.com。下面的htaccess代码可以做到这一点:

RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

但是,有没有一种方法可以在不硬编码域名的通用方式做到这一点呢?


当前回答

使用:Javascript / jQuery

// similar behavior as an HTTP redirect
window.location.replace("http://www.stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";

或. htaccess:

RewriteEngine On
RewriteBase /
Rewritecond %{HTTP_HOST} ^www\.yoursite\.com$ [NC]
RewriteRule ^(.*)$ https://yoursite.com/$1 [R=301,L]

PHP方法:

$protocol = (@$_SERVER["HTTPS"]    == "on") ? "https://" : "http://";

if (substr($_SERVER['HTTP_HOST'], 0, 4) !== 'www.') {
    header('Location: '.$protocol.'www.'.$_SERVER    ['HTTP_HOST'].'/'.$_SERVER['REQUEST_URI']);
    exit;
}

Ajax

$.ajax({
    type: "POST",
    url: reqUrl,
    data: reqBody,
    dataType: "json",
    success: function(data, textStatus) {
        if (data.redirect) {
            // data.redirect contains the string URL to redirect to
            window.location.href = data.redirect;
        }
        else {
            // data.form contains the HTML for the replacement form
            $("#myform").replaceWith(data.form);
        }
    }
});

其他回答

如果.htaccess定制不是理想的选择:

我创建了简单的重定向服务器供公众使用。只需添加A或CNAME记录:

CNAME   r.simpleredirect.net
A       89.221.218.22

更多信息:https://simpleredirect.net

以下是将一个www URL重定向到no-www的规则:

#########################
# redirect www to no-www
#########################

RewriteCond %{HTTP_HOST} ^www\.(.+) [NC]
RewriteRule ^(.*) http://%1/$1 [R=301,NE,L]

以下是将一个no-www URL重定向到www的规则:

#########################
# redirect no-www to www
#########################

RewriteCond %{HTTP_HOST} ^(?!www\.)(.+) [NC]
RewriteRule ^(.*) http://www.%1/$1 [R=301,NE,L]

注意,我使用了NE标志来防止apache转义查询字符串。如果没有这个标志,apache将把请求的URL http://www.example.com/?foo%20bar更改为http://www.example.com/?foo%2250bar

试试这个:

RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^(.*)$ %{HTTP_HOST}$1 [C]
RewriteRule ^www\.(.*)$ http://$1 [L,R=301]

如果主机以www开头,我们将整个主机粘贴到URL的开头,然后去掉“www”。

使用。htaccess重定向到www或非www:

只需将以下代码行放入您的主根.htaccess文件中。 在这两种情况下,只需将domain.com更改为您自己的主机名。

重定向到www

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{HTTP_HOST} ^domain\.tld [NC]
  RewriteRule ^(.*)$ http://www.domain.tld/$1 [L,R=301]
</IfModule>

重定向到非www

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{HTTP_HOST} ^www\.domain\.tld [NC]
  RewriteRule ^(.*)$ http://domain.tld/$1 [L,R=301]
</IfModule>
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^/(.*)$ https://%1/$1 [R]

RewriteCond捕获www后HTTP_HOST变量中的所有内容。并将其保存在%1中。

RewriteRule捕获了没有/开头的URL,并将其保存在$1中。