Redirecting www to non-www (apache, letsencrypt )

apache-2.4lets-encryptrewritessl-certificate

Ubuntu 14.04
Apache 2.4.18

I have set up a SSL certificate using letsencrypt. It works well but in order to work, I cannot have multiple vhost defined in one virtualhost configuration file. Each vhost has to sit in its own .conf file inside /etc/apache2/sites-available.

I need to make sure all requests to www.example.com are redirected to example.com.
Since I need to solve it inside the unique virtualhost file, I'm trying to include a rewrite rule inside to perform the redirection but so far it fails silently: all https://www.example.com requests are not being redirected to https://example.com and a "insecure website" warning is displayed.

Here is the virtualhost configuration file for domain.com-le-ssl.conf.

<IfModule mod_ssl.c>
<VirtualHost *:443>
        ServerName example.com
        ServerAlias www.example.com

        RewriteEngine on
        RewriteCond %{HTTP_HOST} ^www\.(.+) [NC]
        RewriteRule ^ https://%1%{REQUEST_URI} [L,R=301]

        DocumentRoot /home/user_account/www/example.com/public
        <Directory /home/user_account/www/example.com/public>
                Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

        ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9000/home/user_account/www/example.com/public/$1

SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
</IfModule>

Best Answer

Since your SSL certificate is not valid for www.example.com, when someone accesses your site using www.example.com, they will get a certificate warning. This happens regardless of whether they are served a redirect or not. Otherwise, it would be possible to create a redirect to any site at all and it would look trustworthy.

What you need to do is to either get a certificate that covers both www.example.com and example.com, or to set up a separate virtualhost for www.example.com, with a valid certificate, and put the redirect in that virtualhost.