我想将www.example.com重定向到example.com。下面的htaccess代码可以做到这一点:
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]
但是,有没有一种方法可以在不硬编码域名的通用方式做到这一点呢?
我想将www.example.com重定向到example.com。下面的htaccess代码可以做到这一点:
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]
但是,有没有一种方法可以在不硬编码域名的通用方式做到这一点呢?
当前回答
添加如果localhost,忽略重定向(用于本地环境中的开发目的)。如果不是localhost AND(不是https或它是www),重定向到https和非www。
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !localhost [NC]
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
其他回答
更新后可以在Apache 2.4上工作:
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
与Michael的唯一变化是删除[NC],这会产生“AH00665”错误:
不支持非正则表达式模式“-f”的NoCase选项,将被忽略
但是如果我们需要为单独的http和https这样做:
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
嗨,你可以在你的htaccess文件上使用以下规则:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
选择的答案和许多其他解决方案在这里放弃了url的部分后/,所以基本上它总是重定向到主域,至少对我来说。所以我在斜杠后添加关于全路径的工作样本..
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1%{REQUEST_URI} [L,R=301]
如果你想在httpd.conf文件中这样做,你可以在没有mod_rewrite的情况下这样做(显然这样对性能更好)。
<VirtualHost *>
ServerName www.example.com
Redirect 301 / http://example.com/
</VirtualHost>
我在这里得到了答案:https://serverfault.com/questions/120488/redirect-url-within-apache-virtualhost/120507#120507