Search code examples
apachehttphttpsvirtualhostno-www

HTTP + HTTPS + www + non-www Apache config


In my Apache configuration, everything is redirected to HTTPS (which is good). But both https://www.example.com and https://example.com still exist.

Question: how to have only https://www.example.com and not the non-www?

Should I use a 301 Redirection or another technique?

How should such a configuration be changed:

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

?


Solution

  • One way to do it is to change the current virtual host ServerName www.example.com and add a new Virtual Host for the non-www

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