Apache 2:将根URL从http重定向到https时出现问题

ltskdhd1  于 2022-12-04  发布在  Apache
关注(0)|答案(2)|浏览(190)

我从http站点重定向到https站点时遇到问题。
这个index.php文件在根文件夹中,重定向到一个subler:

<?php
header("Location: /news/");
?>

这url https://www.example.com被正确地重定向到https://www.example.com/news/
这url https://www.example.com/index.php被正确地重定向到https://www.example.com/news/
这url http://www.example.com/index.php被正确地重定向到https://www.example.com/news/
然而,url http://www.example.com显示的是一个空目录,如下图所示:

以下是配置文件:

/etc/apache 2/站点可用/www.示例.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>

/etc/apache 2/站点可用/www.示例.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重定向到https://www.example.com/news/

a0x5cqrl

a0x5cqrl1#

一个有两个选项--虚拟主机重定向和请求重写。根据您的需要调整以下配置片段。

虚拟主机重定向

更简单、更安全。* 通过虚拟主机配置将HTTP虚拟主机(端口80)重定向 * 到HTTPS虚拟主机(端口443):

# Listening for HTTP connections
<VirtualHost *:80>
    ServerName www.example.com
    ServerAlias example.com

    # permanently redirects to the site's HTTPS version
    Redirect permanent / https://www.example.com/
</VirtualHost>

# Listening for HTTPS connections
<VirtualHost _default_:443>
    ServerName www.example.com
    ServerAlias example.com
    DocumentRoot /usr/local/apache2/htdocs
    SSLEngine On

    # Further configurations...
</VirtualHost>

请求重写

或者--通常,当虚拟主机配置不可访问时--可以编辑.htaccess文件(如果需要,创建它)来 * 重写 * HTTP到HTTPS请求。

LoadModule rewrite_module modules/mod_rewrite.so

httpd.conf中必须设置(通常默认情况下设置)。然后添加到.htaccess文件:

# Enable rewriting
RewriteEngine On 
# Check for HTTPS, if no, execute next line
RewriteCond %{HTTPS} off
# Redirect to HTTPS with status code 301 (moved permanently)
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [L,R=301]
pqwbnv8z

pqwbnv8z2#

我用了:

<VirtualHost *:80>
        RewriteEngine On
        RewriteCond %{HTTPS} !=on
        RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R=301,L]
</virtualHost>

在conf文件中键入代码。

相关问题