【问题标题】:Detect the domain name automatically in .htaccess在 .htaccess 中自动检测域名
【发布时间】:2014-02-02 12:54:18
【问题描述】:

我想删除 www 并直接指向域的非 www 版本,经过一些研究,我发现下面这两行可以完成这项工作:

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

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

我发现这个article 可能是这个问题的答案,但我只是不知道如何实施它我不是真正的专家,但我知道一个错误会破坏一切,请帮助。

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]

【问题讨论】:

    标签: php apache .htaccess mod-rewrite


    【解决方案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]
    

    【讨论】:

    • 我测试过,它们可以工作。 OP注意:301是永久重定向并被浏览器缓存,如果您想尝试不同的设置,请先使用重定向302,当您得到您想要的时更改为301。
    • @eis 谢谢 ;-) 删除了“未测试”消息:P
    • @Loai 在重写规则的末尾,您会看到重定向的 HTTP 状态代码。 301是永久的,302是临时的。我的意思是,在测试时,您可以使用 302 而不是此处显示的 301。
    • 301 是“永久移动”的状态码。对于最终站点,这是发送到浏览器的正确代码。出于测试目的,您应该使用[R=302] 或简单地发送[R] 发送状态代码302(暂时移动)。浏览器不会缓存临时重定向,这意味着如果您更改某些内容,您会直接看到更改。永久重定向(有时)被缓存,这意味着如果您进行更改,似乎什么都不会发生,因为新的 url 实际上是从浏览器缓存加载的,而不是从服务器加载的。
    • @Loai 您通常可以通过左上角的 StackOverflow 下拉菜单访问聊天,点击“聊天”。要与某人开始一对一对话,请在 cmets 中将对话延长足够长的时间,直到它开始建议聊天室或单击某人的名字,在 URL 前添加 chat.(例如 this 为您)和为你们俩创建一个聊天室。我不确定对方是否收到通知,所以请在评论部分留下@消息,并附上指向该聊天室的链接。
    猜你喜欢
    • 2013-10-25
    • 2019-09-18
    • 2012-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多