HTTP + HTTPS + www + 非 www Apache 配置

HTTP + HTTPS + www + non-www Apache config

在我的 Apache 配置中,所有内容都重定向到 HTTPS(这很好)。但是 https://www.example.comhttps://example.com 仍然存在。

问题:如何只有https://www.example.com而没有非www?

我应该使用 301 Redirection 还是其他技术?

这样的配置应该怎么改:

<VirtualHost *:80>
  ServerName example.com
  ServerAlias *.example.com
  RewriteEngine on
  RewriteCond %{HTTPS} !on
  RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</VirtualHost>

<IfModule mod_ssl.c>
<VirtualHost *:443>
  ServerName example.com
  ServerAlias *.example.com
  DocumentRoot /home/www/example
  <Directory />
    Options FollowSymLinks
    AllowOverride All
    Order deny,allow
    Allow from all
    Require all granted
  </Directory>
  SSLCertificateFile /etc/letsencrypt/live/example.com/cert.pem
  SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
  Include /etc/letsencrypt/options-ssl-apache.conf
  SSLCertificateChainFile /etc/letsencrypt/live/example.com/chain.pem
</VirtualHost>
</IfModule>

?

一种方法是更改​​当前的虚拟主机 ServerName www.example.com 并为非 www

添加一个新的虚拟主机

<VirtualHost *:443> ServerName example.com Redirect 301 / https://www.example.com/ </VirtualHost>

解决了问题,但它还需要存在证书行(否则会失败):

<VirtualHost *:443>
    ServerName example.com
    Redirect 301 / https://www.example.com/
    SSLCertificateFile /etc/letsencrypt/live/example.com/cert.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
    Include /etc/letsencrypt/options-ssl-apache.conf
    SSLCertificateChainFile /etc/letsencrypt/live/example.com/chain.pem
</VirtualHost>