【问题标题】:apache2 cannot redirect non-www to www within virtual hostapache2 无法将非 www 重定向到虚拟主机中的 www
【发布时间】:2025-12-01 01:40:01
【问题描述】:

我在 tomcat(6) 前面有一个 apache (2.4.6) 服务器。我希望对 www.domain.com 的所有请求都永久重定向到 domain.com。我目前的配置是:

<VirtualHost *:80>
ServerName www.domain.ma
RewriteEngine on
RewriteCond %{HTTP_HOST} ^domain\.ma
RewriteRule ^(.*)$ http://www.domain.ma/$1 [R=permanent,L]

DocumentRoot /var/www/domain.ma/htdocs

ProxyRequests Off
ProxyPreserveHost On

ProxyPassReverseCookiePath /portal /
ProxyPass /portal/index.htm http://127.0.0.1:8080/portal/index.htm

ProxyPass /images !
ExpiresByType image/* A2592000

</VirtualHost>

当我请求 http://domain.ma/ 时,apache 不会重定向到 http://www.domain.ma/,有人可以告诉我我的配置文件有什么问题吗?

【问题讨论】:

  • 请注意,您的 http_host 正则表达式并不完全正确。如果有人设法将domain.masite.example.com 指向您的服务器,您仍然会重定向,因为您只匹配主机名的开头,而不是整个字符串。

标签: tomcat mod-rewrite apache2 virtualhost


【解决方案1】:

试试这个:

ServerName domain.ma
ServerAlias www.domain.ma 

RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\.domain\.ma [NC]
RewriteRule (.*) http://www.domain.ma/$1 [R=301,L]

【讨论】:

  • 使用“ist”解决方案我遇到了一个小问题:domain.ma/path 被重定向到domain.ma//path:双斜杠。我通过在 RewriteRule (.*) domain.ma$1 [R=301,L] 中替换 RewriteRule (.*) domain.ma/$1 [R=301,L] 来纠正它
  • @user973296 如果没有 ServerAlias,Apache 将不会知道这个 VirtualHost 适用于 www.domain.ma 和 domain.ma
  • @user973296 对不起,忘记了RewriteBase
  • 我可能会反过来命名它。即ServerName www.domain.ma ServerAlias domain.ma 因为www. 是主要的。 - 只是美学。
最近更新 更多