Apache 2.4 – Force HTTPS Domain to HTTPS www.Domain Rewrite

apache-2.4Wordpress

After setting up Apache 2.4 and WordPress, I’m getting the following SSL error message:

$ wget "https://example.com"
Resolving example.com (example.com)... 192.168.15.5
Connecting to example.com (example.com)|192.168.15.5|:443... connected.
ERROR: no certificate subject alternative name matches
requested host name ‘ example.com’.
To connect to example.com insecurely, use `--no-check-certificate'.

To make the domain name match my SSL certificate ( www.example.com), I tried to tweak the site configuration to redirect https://example.com to https://www.example.com. It isn’t working though: The http-to-https redirects function as expected, but naked-domain to www-domain does not.

Here’s my site configuration:

<VirtualHost *:80>
        ServerName example.com
        ServerAlias www.example.com
        Redirect permanent / https://www.example.com/
</VirtualHost>
                                                                                                  
<IfModule mod_ssl.c>
        <VirtualHost _default_:443>
            ServerName www.example.com

            Protocols h2 http/1.1

            ServerAdmin webmaster@localhost
            DocumentRoot /var/www/html
            DirectoryIndex index.php

            RewriteEngine on            #### Doesn’t work at all ####
            RewriteCond %{HTTP_HOST} ^example\.com [NC]
            RewriteRule ^/(.*) https://www.example.com/$1 [L,R=301]


            ErrorLog ${APACHE_LOG_DIR}/error.log
            CustomLog ${APACHE_LOG_DIR}/access.log combined

            # SSL with Letsencrypt                                                                                                                Include /etc/letsencrypt/options-ssl-apache.conf
            SSLEngine on
            SSLCertificateFile      /etc/letsencrypt/live/www.example.com/fullchain.pem
            SSLCertificateKeyFile /etc/letsencrypt/live/www.example.com/privkey.pem
                                                                             
    </VirtualHost>
</IfModule>

The site itself works fine, and .htaccess contains only the lines created by WordPress.

Any input is appreciated.

Best Answer

You still need a valid certificate for http://example.com. The redirect happens after a valid TLS connection is established.

Grab a certificate for example.com with www.example.com in the SAN field.

Related Topic