Apache 2:HTTP根URL无法正确重定向至HTTPS的问题解决
问题:HTTP站点根路径无法正确重定向到HTTPS子路径
根目录下的index.php负责将请求重定向到子路径,代码如下:
<?php header("Location: /news/"); ?>
当前正常重定向场景
https://www.example.com可正确跳转至https://www.example.com/news/https://www.example.com/index.php可正确跳转至https://www.example.com/news/http://www.example.com/index.php可正确跳转至https://www.example.com/news/
异常场景
访问http://www.example.com时,页面显示为空目录列表,未触发预期的重定向。
相关Apache配置文件
HTTP站点配置(/etc/apache2/sites-available/www.example.com.conf)
<VirtualHost *:*> ServerName www.example.com DocumentRoot /var/www/vhosts/example.com/httpdocs ServerAlias example.com RewriteEngine on RewriteCond %{SERVER_NAME} =example.com [OR] RewriteCond %{SERVER_NAME} =www.example.com RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost>
HTTPS站点配置(/etc/apache2/sites-available/www.example.com-le-ssl.conf)
<IfModule mod_ssl.c> <VirtualHost *:443> ServerName www.example.com DocumentRoot /var/www/vhosts/example.com/httpdocs ServerAlias example.com Include /etc/letsencrypt/options-ssl-apache.conf SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem </VirtualHost> </IfModule>
解决方案
问题核心:访问http://www.example.com时,Apache未优先加载index.php作为默认首页,而是直接列出目录内容,导致未触发PHP的重定向逻辑。可通过以下两种方式解决:
方式一:指定HTTP站点的默认首页
修改/etc/apache2/sites-available/www.example.com.conf,在DocumentRoot下方添加DirectoryIndex指令,强制Apache优先加载index.php:
<VirtualHost *:*> ServerName www.example.com DocumentRoot /var/www/vhosts/example.com/httpdocs ServerAlias example.com # 添加默认首页规则 DirectoryIndex index.php index.html RewriteEngine on RewriteCond %{SERVER_NAME} =example.com [OR] RewriteCond %{SERVER_NAME} =www.example.com RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost>
方式二:直接在重写规则中处理根路径跳转
如果不想依赖默认首页配置,可修改HTTP站点的Rewrite规则,直接将根路径请求重定向到目标HTTPS地址:
<VirtualHost *:*> ServerName www.example.com DocumentRoot /var/www/vhosts/example.com/httpdocs ServerAlias example.com RewriteEngine on # 优先处理根路径的跳转 RewriteRule ^/$ https://%{SERVER_NAME}/news/ [END,NE,R=permanent] # 处理其他路径的HTTPS跳转 RewriteCond %{SERVER_NAME} =example.com [OR] RewriteCond %{SERVER_NAME} =www.example.com RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost>
修改完成后,重启Apache服务使配置生效:
sudo systemctl restart apache2
内容的提问来源于stack exchange,提问作者Daniele B
相关产品推荐
相关产品推荐

