301 重定向在新服务器上不起作用

301 Redirect not working on new server

我们 运行 Apache 服务器位于 Linux。

在 Apache 配置文件的 <VirtualHost> 中(在 /etc/apach2/sites/site.conf 中),我们有以下重写规则:

此规则的目的是,如果任何人访问该站点(可以通过多个域访问)尝试在前面没有 www. 的情况下访问,它将 301 重定向到 www.。例如,如果用户访问站点 http://example.com,规则将 301 重定向到 http://www.example.com.

RewriteEngine on

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^([a-z.]+)$ [NC]
RewriteRule ^(.*)$ http://www.%1/ [R=301,L]

我们在其他服务器上设置了相同的规则并且运行良好,但出于某种原因我们无法在这个新服务器上运行它。重新启动 Apache 没问题等等。但是当我们使用 example.com 访问站点时,它不会重定向到 www.example.com.

有什么建议或以前的经验可以提供一些病因线索吗?

=========

这是上下文配置的扩展版本。

<Directory />
                Options FollowSymLinks
                AllowOverride None
        </Directory>
        <Directory /var/www/site/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all

                RewriteEngine on

                # force www
                RewriteCond %{HTTP_HOST} !^www\. [NC]
                RewriteCond %{HTTP_HOST} ^([a-z.]+)$ [NC]
                RewriteRule ^(.*)$ http://www.%1/ [R=301,L]

                # Bypass images, css, javascript and docs, add your own extensions if needed.
                RewriteCond %{REQUEST_URI} \.(bmp|gif|jpe?g|png|css|js|txt|pdf|doc|xls|ico)$
                RewriteRule ^(.*)$ - [NC,L]

                # The ColdBox index.cfm/{path_info} rules.
                RewriteRule ^$ index.cfm [QSA,NS]
                RewriteCond %{REQUEST_FILENAME} !-f
                RewriteCond %{REQUEST_FILENAME} !-d
                RewriteRule ^(.*)$ index.cfm/%{REQUEST_URI} [QSA,L,NS]

        </Directory>

Comment: I've added the RewriteRule as you suggested.. and that seems to be rewriting fine. 119.9.30.242/foo rewrites to http://119.9.30.242/bar?host=119.9.30.242

但是在你说的问题中:

...but when we access the site with example.com, it is not redirecting to www.example.com

您似乎是通过 IP 地址而非域名访问网站?!

如果您通过 IP 地址(而不是域名)访问站点,那么这显然不会重定向,因为前面的 RewriteCond 指令验证了主机名:

RewriteCond %{HTTP_HOST} ^([a-z.]+)$ [NC]

这只允许由字母和点组成的主机名,不允许数字或连字符(正如我在之前的评论中提到的),因此这将排除 IP 地址被重定向。 (正确的是,http://www.119.9.30.242/ 将无效。)

更新: 要 allow/redirect 带有数字(和连字符)的域,那么您需要将上面的 directive/regex 更改为:

RewriteCond %{HTTP_HOST} ^([a-z0-9.-]+)$ [NC]