1

I have one Apache server with many VirtualHosts in various conf files. I thought I could define a blanket rule to redirect all traffic to all of those hosts to HTTPS and non-www urls.

Unfortunately, the configuration below (which I have in my 000-default.conf file) only partially works. It works for urls that start with http://www.domain, https://domain (no www) and https://www.domain. It does not work for those that start with http://domain. Apache throws a 403 Forbidden (no access to / on this server).

As a bonus, the redirects also add an extra trailing slash that I'd like removed.

<VirtualHost *:443>
        SSLEngine on
        SSLCertificateFile /etc/letsencrypt/live/domain/cert.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/domain/privkey.pem
        SSLCertificateChainFile /etc/letsencrypt/live/domain/chain.pem
</VirtualHost>

<VirtualHost *:80>
        RewriteEngine on
        RewriteCond %{HTTP_HOST} ^www\.?(.*)$ [NC]
        RewriteRule ^(.*)$ https://%1/$1 [R=301,NC]
</VirtualHost>
bluppfisk
  • 121
  • 5

2 Answers2

0

If you can't duplicate configuration for vHosts you can try to setup this in this way as described here: Serve http (port 80) and https (port 443) on same VirtualHost

mariaczi
  • 236
  • 1
  • 5
0

This does it. Took me a while to understand RewriteRules syntax as well as that I cannot use RedirectMatch (which Apache recommends) in this case.

<VirtualHost *:443>
        ServerAlias www.*
        SSLEngine on
        SSLCertificateFile /etc/letsencrypt/live/blaap.be/cert.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/blaap.be/privkey.pem
        SSLCertificateChainFile /etc/letsencrypt/live/blaap.be/chain.pem

        RewriteEngine on
        RewriteCond %{HTTP_HOST} ^(www\.)*(.*)$ [NC]
        RewriteRule ^/(.*)$ https://%2/$1 [R=301,NC,L]
</VirtualHost>

<VirtualHost *:80>
        RewriteEngine on
        RewriteCond %{HTTP_HOST} ^(www\.)*(.*)$ [NC]
        RewriteRule ^/(.*)$ https://%2/$1 [R=301,NC,L]
</VirtualHost>
bluppfisk
  • 121
  • 5