使用 .htaccess 和 mod_rewrite 将 HTTP 重定向到 HTTPs

使用 .htaccess 和 mod_rewrite 将 HTTP 重定向到 HTTPs

我知道网上有很多关于使用 .htaccess 将 HTTP 重定向到 HTTPS 的教程和帖子。但我的问题是关于重定向期间会更改的 URL。

Apache2 应该转发“http://localhost/~用户/secure_secrets“ 到https://localhost/~user/secure_secrets“。我已安装 apache_2,并使用 userdir 模块从用户主目录提供 public_html。现在,在 public_html 中,我有一个名为“secure_secrets”的文件夹,URL 指向该文件夹。对于重定向,我已将 .htaccess 设置为:

# Enable rewrite
RewriteEngine on

# Check if connection is not already HTTPS
RewriteCond %{HTTPS} !=on

RewriteRule ^/?secure_secrets/(.*) https://localhost/~user/secure_secrets/$1 [R,L]

但它不起作用。当我在浏览器中输入 HTTP URL 时,它显示 404 未找到。我认为我在重写 URL 中指定 HTTP URL 时犯了一个错误,但我不明白在哪里。

作为额外信息,我的其他配置是:

在/etc/apache2/sites-available/000-default.conf中:

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

和/etc/apache2/mods-enabled/userdir.conf:

    <IfModule mod_userdir.c>
        UserDir public_html
        UserDir disabled root

        <Directory /home/*/public_html>
                AllowOverride All
                Options MultiViews Indexes SymLinksIfOwnerMatch
                <Limit GET POST OPTIONS>
                        Order allow,deny
                        Allow from all
                </Limit>
                <LimitExcept GET POST OPTIONS>
                        Order deny,allow
                        Deny from all
                </LimitExcept>
        </Directory>
</IfModule>

我希望有人能帮我解决这个问题?提前谢谢!

答案1

您的 RewriteRule 指令正在寻找以正斜杠开头、后跟“secure_secrets”或仅以“secure_secrets”开头的 URL - 您没有在任何地方提及“~user”部分。

RewriteRule ^/?secure_secrets/(.*) https://localhost/~user/secure_secrets/$1 [R,L]

根据您的描述,这似乎是您想要的:

RewriteRule ^/~user/secure_secrets/(.*) https://localhost/~user/secure_secrets/$1 [R,L]

答案2

网上有很多关于重定向的教程和帖子,但我敢打赌,没有一个建议重定向到 localhost。而且看起来你正在这样做。从浏览器机器的角度来看是 Localhost。因此,您看到的 404 是由您的本地 Web 服务器发出的。

相关内容