My web server is in the cloud, a VPS on Vultr. I have added the following lines to my apache.conf file:
Options -Indexes +FollowSymLinks
AllowOverride All
Require all granted
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)
RewriteRule ^.*$ https://%1/$1 [R=301,L]
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]
These lines will redirect an http://www.example.com
or an http://example.com
to an https://example.com
. It works very well. I do not use htaccess files.
I always try to think how a user could mess things up and in this case, I think they could enter https://www.example.com
. And sure enough, it messes things up.
I want to add that I only have a LetsEncrypt certificate for the example.com
domain. I do not have one for the www.example.com
subdomain, like many others add to their server.
In the sites available file for the domain /etc/apache2/sites-available/example.com.conf
I have:
<VirtualHost example.com:80>
ServerAdmin admin@example.com
ServerName example.com
ServerAlias example.com
# above line eliminates www.example.com
DocumentRoot /var/www/example.com
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
I do not use a VirtualHost file for the 443 port.
I have read other stackoverflow comments and questions about the issue of https://www.example.com
. I reference a near identical request that does not eliminate my problem, but maybe they have a certificate for the www subdomain, allowing the proposed solution there to work. Best Practice: 301 Redirect HTTP to HTTPS (Standard Domain)
My assumption is that possibly:
- My apache.conf code has an error.
- I need an additional certificate for the www subdomain.
- Some other solution.
What is the best way to proceed here? Or do others just ignore this since it will be overshadowed by the browser screaming about how unsafe the site is?