如何停止重定向循环? Ubuntu 上的 Apache2

How do I stop a Redirect Loop? Apache2 on Ubuntu

我有一个 DigitalOcean Ubuntu 20.04 Droplet。连接到来自 Namecheap 的域和 SSL 证书。一切正常。我正在尝试添加来自 http://example.com to https://www.example.com 的重定向。 HTTPS 和万维网。当我尝试我的域时。我收到一条错误消息,提示“重定向太多”。我无法访问该页面。没有阿帕奇。所以我在重定向循环中。在 www 和非 www 之间。我的 /etc/apache2/sites-enabled/000-default.conf 是:

`<VirtualHost *:80>
      ServerName example.com
      Redirect permanent / https://www.example.com/
 </VirtualHost>
 <VirtualHost *:443>
      ServerName example.com
      Redirect permanent / https://www.example.com/
      DocumentRoot /var/www/html
      SSLEngine on
      SSLCertificateFile /etc/ssl/example_com.crt
      SSLCertificateKeyFile /etc/ssl/example_com.key
      SSLCertificateChainFile /etc/ssl/example_com.ca-bundle
 </VirtualHost>`

那么,如何停止重定向循环?我还有 /etc/apache2/sites-enabled/000-default.conf:30

 `<VirtualHost *:443>
       ServerName example.com
       DocumentRoot /var/www/html
       SSLEngine on
       SSLCertificateFile /etc/ssl/example_com.crt
       SSLCertificateKeyFile /etc/ssl/example_com.key
       SSLCertificateChainFile /etc/ssl/example_com.ca-bundle
  </VirtualHost>`

这看起来正确吗?请看一下。并回复。我如何停止重定向。环形。谢谢

调整您的虚拟主机配置:

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

<VirtualHost *:443>
  ServerName example.com
  ServerAlias www.example.com
  DocumentRoot /var/www/html
  SSLEngine on
  SSLCertificateFile /etc/pki/tls/certs/example_com.crt
  SSLCertificateKeyFile /etc/pki/tls/private/example_com.key
  RewriteEngine On
  RewriteCond %{HTTP_HOST} !^www\. [NC]
  RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</VirtualHost>

得到以下结果:

http://example.com -> https://www.example.com
http://www.example.com -> https://www.example.com
https://example.com -> https://www.example.com
https://www.example.com -> Stays the same