Basj
Basj

Reputation: 46363

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>

?

Upvotes: 0

Views: 54

Answers (2)

Basj
Basj

Reputation: 46363

Relymcd's answer solved the problem, but it also needs the certificate lines to be present (if not it will fail):

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

Upvotes: 1

relytmcd
relytmcd

Reputation: 244

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>

Upvotes: 0

Related Questions