首页 > 解决方案 > HTTP + HTTPS + www + 非 www Apache 配置

问题描述

在我的 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>

?

标签: apachehttphttpsvirtualhostno-www

解决方案


Relymcd 的回答解决了这个问题,但它还需要存在证书行(如果没有,它将失败):

<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>

推荐阅读