Apache VHost redirect aliases to HTTPS
I'm trying to do Virtualhosts on my "playground" VPS.
I need it to redirect 3 or more domains to the main one.
Also it should redirect HTTPS, Lets Encrypt is configured and working well.
In current state, this config works fine, BUT when user goes to HTTPS secsite.com manually (entering HTTPS himself), it redirects to mainsite first and then redirects again back to secsite.com.
<VirtualHost *:80>
ServerName mainsite.com
ServerAlias *.mainsite.com secsite.com *.secsite.com
RewriteRule !https:\/\/mainsite\.com https://mainsite.com%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>
<IfModule mod_ssl.c>
<VirtualHost *:443>
ServerName mainsite.com
ServerAlias *.mainsite.com secsite.com *.secsite.com
RewriteRule !https:\/\/mainsite\.com https://mainsite.com%{REQUEST_URI} [END,NE,R=permanent]
ServerAdmin webmaster@localhost
DocumentRoot /var/www/mainsite.com
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
SSLCertificateFile /etc/letsencrypt/live/mainsite.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/mainsite.com/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
</IfModule>
Any idea how to get this work?
RewriteRule !https:\/\/mainsite\.com https://mainsite.com%{REQUEST_URI} [END,NE,R=permanent]
The RewriteRule
directive matches against the URL-path only, not the scheme + hostname, as you are trying to do here. Since you have negated the pattern (!
prefix), it will always be successful and result in a redirect loop. That is, if it is doing anything at all...
You've not enabled the rewrite engine (ie. RewriteEngine On
), so unless this is enabled earlier in the config, these RewriteRule
directives are simply going to be ignored.
If you are seeing any redirect at all, either you are seeing a cached response from an earlier attempt (note that 301 redirects are cached persistently by the browser), or your application (or something else) is triggering the redirect.
The redirect in your vHost:80 (HTTP) should be an unconditional mod_alias Redirect
, since you are redirecting everything to HTTPS. For example:
<VirtualHost *:80>
ServerName mainsite.com
ServerAlias *.mainsite.com secsite.com *.secsite.com
Redirect 301 / https://mainsite.com/
</VirtualHost>
The Redirect
directive is prefix-matching and everything after the match is copied onto the end of the target URL. eg. http://example.com/foo/bar
is redirected to https://mainsite/foo/bar
.
For the vHost:443 (HTTPS) you need to redirect when the requested hostname is not the canoncial host. For this you need to use an additional RewriteCond
directive and check against the HTTP_HOST
server variable. For example:
<IfModule mod_ssl.c>
<VirtualHost *:443>
ServerName mainsite.com
ServerAlias *.mainsite.com secsite.com *.secsite.com
RewriteEngine On
RewriteCond %{HTTP_HOST} !^mainsite\.com$
RewriteRule ^ https://mainsite.com%{REQUEST_URI} [END,NE,R=permanent]
: