Apache Configuration – Redirecting Non-WWW to WWW HTTPS

apache-2.4virtualhost

I have a site, www.example.com, that I can't visit without entering the www. Using an Apache Virtual Host, I'm trying to make it so if non-www is entered, it's automatically redirected to www.

If I try going to http://www.example.com, it redirects to https://www.example.com and works

If I try going to https://www.example.com, it also works.

However, the problem is:

If I enter http://example.com, it redirects to https://example.com and says:

This site can’t be reached Check if there is a typo in example.com.
If spelling is correct, try running Windows Network Diagnostics.
DNS_PROBE_FINISHED_NXDOMAIN

I get the same message if I try going to https://example.com

The problem is my site only works with "www." On non-www, how can I force www.? I was trying the following to no avail:

<VirtualHost *:80>
    ServerName example.com
    Redirect permanent / https://www.example.com/
</VirtualHost>
<VirtualHost *:443>
    ServerName www.example.com
    ServerAlias example.com
    DocumentRoot /var/www/example.com/public/

    # Force non-www to www in HTTPS.
    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

    SSLEngine On
    SSLCertificateFile /etc/letsencrypt/live/example.com/cert.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
    SSLCertificateChainFile /etc/letsencrypt/live/example.com/chain.pem

    ErrorLog /var/log/httpd/example.com.error.log
    CustomLog /var/log/httpd/example.com.access.log combined
</VirtualHost>

Best Answer

I don't believe this is an issue with Apache. It's more likely that your authoritative DNS simply doesn't have an entry for the non-WWW version of your web site. For instance, nslookup www.example.com will return the IP address of your server. If you do nslookup example.com it should also return the IP address of your server; if it doesn't, fix that first.

Related Topic