【问题标题】:How to redirect http://example.com to https://example.com in apache2.conf using VirtualHost如何使用 VirtualHost 将 http://example.com 重定向到 apache2.conf 中的 https://example.com
【发布时间】:2021-12-27 14:41:05
【问题描述】:

我正在尝试将 http URL 重定向到 https,并将 www URL 重定向到非 www。 我正在使用在 Raspberry Pi 3 模型 B+ 中运行的最新版本的 Apache 2 http 服务器。

我想在 apache2.conf 中使用 VirtualHosts,因为我在很多地方读到这种方法比使用 .htaccess 更受欢迎

我得到 3 次重定向以正常工作:

http://www.example.com 转到https://example.com

https://example.com 转到https://example.com

https://www.example.com 转到https://example.com

但是 http://example.com 转至http://example.com

换句话说,非 www 不安全 (http) 站点不会被重定向 到安全 (https) 站点...我无法加载我的 SSL 证书。

我使用 CNAME 将 www 网站重定向到非 www。

http 使用重定向指令到达 https。

这是我的 apache2.conf 文件的相关部分:

<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com
Redirect / https://example.com/
</VirtualHost>

<VirtualHost *:443>
ServerName example.com
ServerAlias www.example.com
Protocols h2 http/1.1
ErrorLog logs/error_log
SSLEngine on
SSLCertificateFile /etc/ssl/example.com.crt
SSLCertificateKeyFile /etc/ssl/example_com_key.txt
SSLCertificateChainFile /etc/ssl/example.com.ca-bundle
SSLUseStapling on
</VirtualHost> 

SSLStaplingCache shmcb:/tmp/stapling_cache(128000)

【问题讨论】:

    标签: apache redirect apache2 virtualhost


    【解决方案1】:

    如果您已为每个域配置文件完成 CERTBOT,这会将您的所有 www 网站重定向到非 www 并保护它们。把它放在目录 /www 部分的 /etc/apache2/apache2.conf 中:

    RewriteEngine On
    RewriteCond %{HTTPS} off [OR]
    RewriteCond %{HTTP_HOST} ^www\. [NC]
    RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
    RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]
    

    插入此代码后,无需对 www 域进行 CERTBOT。只需选择 domain.com 即可。您不需要 htaccess 文件。它们可以通过 AllowOverride None 选择来限制。

    记得重启apache。

    【讨论】:

      猜你喜欢
      • 2015-05-21
      • 2020-09-24
      • 1970-01-01
      • 1970-01-01
      • 2020-12-12
      • 2012-02-20
      • 2016-04-05
      • 1970-01-01
      • 2011-07-06
      相关资源
      最近更新 更多