You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apache2忽略.htaccess文件:实现www转http重定向遇阻

实现www到非www的HTTP重定向并解决.htaccess无效问题

你想把www域名重定向到非www的HTTP地址,但发现Apache忽略了/var/www/html下的.htaccess文件——哪怕已经启用了rewrite模块。咱们一步步拆解问题,给出可行的解决方案。

一、先排查.htaccess无效的核心原因

你的Apache配置里有两个明显的冲突点:

  • <VirtualHost *:80>块内同时存在两个DocumentRoot:先是DocumentRoot /var/www/html,后面又写了DocumentRoot /var/www,Apache会优先加载后者,导致你的.htaccess所在的/var/www/html目录不被当作网站根目录。
  • 虽然你在VirtualHost外配置了<Directory /var/www/html>并设置了AllowOverride All,但由于VirtualHost内的根目录指向了/var/www,这个目录权限配置根本不会作用到当前虚拟主机。

二、推荐方案:直接在VirtualHost中配置重定向(更高效)

比起纠结.htaccess的问题,直接在虚拟主机配置里实现重定向是更优选择——性能更好,也更易维护。修改你的/etc/apache2/sites-enabled/000-default.conf:

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    # 统一网站根目录,指向你的.htaccess所在路径
    DocumentRoot /var/www/html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    ServerName rentauto-sofia.com
    ServerAlias www.rentauto-sofia.com

    # 启用rewrite引擎,实现www到非www的301永久重定向
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^www\.rentauto-sofia\.com$ [NC]
    RewriteRule ^(.*)$ http://rentauto-sofia.com/$1 [R=301,L]

    # 保留你的代理配置
    ProxyPass / http://rentauto-sofia.com:8000/
    ProxyPassReverse / http://rentauto-sofia.com:8000/

    # 配置当前虚拟主机的目录权限
    <Directory /var/www/html>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>
</VirtualHost>

三、如果一定要用.htaccess生效的话

如果你坚持依赖.htaccess,需要先修正000-default.conf的配置冲突:

  1. 删除VirtualHost内多余的DocumentRoot /var/www,确保只有DocumentRoot /var/www/html
  2. 把目录权限配置移到VirtualHost块内部,确保作用于当前虚拟主机:
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    ServerName www.rentauto-sofia.com
    ServerAlias rentauto-sofia.com

    ProxyPass / http://rentauto-sofia.com:8000/
    ProxyPassReverse / http://rentauto-sofia.com:8000/

    <Directory /var/www/html>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>
</VirtualHost>

然后保留你的.htaccess内容不变即可:

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

四、最后一步:重启Apache生效

无论用哪种方案,修改配置后都要重启Apache:

sudo systemctl restart apache2

内容的提问来源于stack exchange,提问作者Dennis Barzanoff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:32:03