我想将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://%1/subfolder/$1 [R=301,L]

的子文件夹

其他回答

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^/(.*)$ https://%1/$1 [R]

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

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

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

如果你强迫www。在url或强制SSL协议中,然后尝试在htaccess文件中使用可能的变体,例如:

RewriteEngine On
RewriteBase /

### Force WWW ###

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

## Force SSL ###

RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://example.com/$1 [R,L]

## Block  IP's ###
Order Deny,Allow
Deny from 256.251.0.139
Deny from 199.127.0.259

我使用上面的规则将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]

以下是将一个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