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

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

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


当前回答

试试这个:

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

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

其他回答

嗨,你可以在你的htaccess文件上使用以下规则:

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

我让它起作用的唯一方法…

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

我不知道你为什么要删除www。 但相反的版本是:

# non-www.* -> www.*, if subdomain exist, wont work
RewriteCond %{HTTP_HOST} ^whattimein\.com
RewriteRule ^(.*)$ http://www.whattimein.com/$1 [R=permanent,L]

这个脚本的优点是: 如果你有test.whattimein.com之类的(开发/测试环境) 它不会将U重定向到原始环境。

WWW到非WWW使用HTTPS

RewriteEngine on

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

RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

使用: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);
        }
    }
});