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

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

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


当前回答

RewriteEngine on
# if host value starts with "www."
RewriteCond %{HTTP_HOST} ^www\.
# redirect the request to "non-www"
RewriteRule ^ http://example.com%{REQUEST_URI} [NE,L,R]

如果你想同时删除http和https上的www,请使用以下方法:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTPS}s ^on(s)|offs
RewriteRule ^ http%1://example.com%{REQUEST_URI} [NE,L,R]

这种重定向 非ssl

http://www.example.com

to

http://example.com

和 SSL

https://www.example.com

to

https://example.com

在apache 2.4上。*你可以使用一个带有if指令的重定向,

<if "%{HTTP_HOST} =='www.example.com'">
Redirect / http://example.com/
</if>

其他回答

选择的答案和许多其他解决方案在这里放弃了url的部分后/,所以基本上它总是重定向到主域,至少对我来说。所以我在斜杠后添加关于全路径的工作样本..

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

我使用上面的规则将www转发到no www,它在主页上工作得很好,但是在内页上他们转发到/index.php

我在我的.htaccess文件中发现了另一个规则,这导致了这个问题,但不知道该怎么做。任何建议都很好:

############################################
## always send 404 on missing files in these folders

    RewriteCond %{REQUEST_URI} !^/(media|skin|js)/

############################################
## never rewrite for existing files, directories and links

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l

############################################
## rewrite everything else to index.php

    RewriteRule .* index.php [L]
RewriteEngine on
# if host value starts with "www."
RewriteCond %{HTTP_HOST} ^www\.
# redirect the request to "non-www"
RewriteRule ^ http://example.com%{REQUEST_URI} [NE,L,R]

如果你想同时删除http和https上的www,请使用以下方法:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTPS}s ^on(s)|offs
RewriteRule ^ http%1://example.com%{REQUEST_URI} [NE,L,R]

这种重定向 非ssl

http://www.example.com

to

http://example.com

和 SSL

https://www.example.com

to

https://example.com

在apache 2.4上。*你可以使用一个带有if指令的重定向,

<if "%{HTTP_HOST} =='www.example.com'">
Redirect / http://example.com/
</if>

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

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

和迈克尔的一样,除了这个有用:P