我的.htaccess文件中有这个:

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

但每当我访问根目录下的文件,比如http://example.com/robots.txt,它就会重定向到http://www.example.comrobots.txt/。

我如何纠正这一点,使它将正确重定向到http://www.example.com/robots.txt?


当前回答

如果可能的话,将其添加到主Apache配置文件中。这是一种重量较轻的解决方案,所需的加工较少。

<VirtualHost 64.65.66.67>
        ServerName example.com
        Redirect permanent / http://www.example.com/
</VirtualHost>
<VirtualHost 64.65.66.67>
   ServerAdmin me@example.com
   ServerName www.example.com
   DocumentRoot /var/www/example
   .
   .
   . etc

因此,“example.com”的独立VirtualHost捕获这些请求,然后永久地将它们重定向到您的主VirtualHost。因此,每个请求都不需要REGEX解析,您的客户端浏览器将缓存重定向,因此它们永远不会(或很少)再次请求“错误”的url,从而节省服务器负载。

注意,Redirect permanent / http://www.example.com/中的末尾斜杠。 如果没有它,来自example.com/asdf的重定向将重定向到http://www.example.comasdf而不是http://www.example.com/asdf。

其他回答

写入。htaccess:)

## Redirect from non-www to www (remove the two lines below to enable)
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

我相信顶部的答案成功地重定向非www到www(例如:mysite.com -> www.mysite.com),但不考虑通配符子域,这导致:

random.mysite.com -> www.random.mysite.com

这里有一个有/没有HTTPS的解决方案

HTTP

RewriteEngine On

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

使用HTTP / HTTPS

RewriteEngine On

RewriteCond %{HTTPS} =on
RewriteRule ^(.*)$ - [env=protocol:https]

RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ - [env=protocol:http]

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

*注:我还没有测试https,因为我目前没有一个证书来测试,但如果有人可以验证或优化我所拥有的,那就太棒了。

以下是支持https和http的正确解决方案:

# Redirect to www
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

乌利希期刊指南。:用于像.co这样的域名。英国,取代

RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$

with

RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+\.[^.]+$

这个配置为我在bitnami wordpress与SSL配置工作:

在/opt/bitnami/apps/wordpress/conf/httpd-app.conf文件中的“RewriteEngine On”下增加了以下内容

RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteBase /
RewriteCond %{HTTPS} !on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www\.domain\.com [NC]
RewriteRule (.*) http://www.domain.com/$1 [L,R=301]

这将重定向您的域名,不是以WWW开始的 它不是重定向你的所有子域。

它很有用。