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

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

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


当前回答

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

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

其他回答

使用。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>

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

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

的子文件夹

但是如果我们需要为单独的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]

如果你想在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