在.htaccess中自动检测域名

时间:2014-02-02 12:54:18

标签: php apache .htaccess mod-rewrite

我想删除www并直接转到域名的非www版本,经过一些研究后我发现下面这两行将完成这项工作:

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

但是,当我将以上两行添加到下面的当前.htaccess文件时,是否需要将domain.com位更改为网站域?如果是这样,我怎么能改变它所以它自己知道域名?所以我不必手动更改它。

我发现这个article和MAYBE回答了这个问题,但我只是不知道如何实现它我不是真正的专家,但我知道一个错误,可以摧毁一切,请帮忙。

DirectoryIndex index.html index.php 
ErrorDocument 404 /404 

RewriteEngine On 
RewriteBase / 

# remove enter code here.php; use THE_REQUEST to prevent infinite loops 
# By puting the L-flag here, the request gets redirected immediately 
RewriteCond %{THE_REQUEST} ^GET\ (.*)\.php\ HTTP 
RewriteRule (.*)\.php$ $1 [R=301,L] 

# remove index 
# By puting the L-flag here, the request gets redirected immediately 
# The trailing slash is removed in a next request, so be efficient and 
# dont put it on there at all 
RewriteRule (.*)/index$ $1 [R=301,L] 

# remove slash if not directory 
# By puting the L-flag here, the request gets redirected immediately 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_URI} /$ 
RewriteRule (.*)/ $1 [R=301,L] 

# add .php to access file, but don't redirect 
# On some hosts RewriteCond %{REQUEST_FILENAME}.php -f will be true, even if 
# no such file exists. Be safe and add an extra condition 
# There is no point in escaping a dot in a string 
RewriteCond %{REQUEST_FILENAME}.php -f 
RewriteCond %{REQUEST_URI} !(/|\.php)$ 
RewriteRule (.*) $1.php [L]

1 个答案:

答案 0 :(得分:1)

如果您只想将www.example.com重定向到example.com,则只需在www.上进行匹配即可。如果你想重定向每个子域(通常不是这种情况),你可以匹配并尝试匹配,如果它有两个部分。通常更容易将example.com更改为您自己的域名。无论如何,您应该在任何其他规则之前添加规则。

#Option 1: Only redirect if it begins with www.
RewriteCond %{HTTP_HOST} ^www\.(.*)$
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

#Option 2: Redirect all the things! (including thingy.sub.domain.example.com to example.com)
RewriteCond %{HTTP_HOST} ^.*\.([^\.]+\.[^\.]+)$
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]