Apache vhosts and Redirecting#
When using Apache’s virtual hosts for the first time it can be easy (at least for me) to make mistake(s) trying to get it a very specific way. For me that specific way was as follows:
Have a main host that lives on a subdomain (this site BTW) that only accepts https.
By default, anything else redirects to the main site…
Except for other virtual hosts
This might seem simple if you a little bit about virtual hosts, which I thought I did before setting this site up.
However, the problem I had today was that I kept either getting forbidden responses or redirected to another other virtual host (Not the one I wanted).
Below is the gist of my working 000-default.conf`
as of writing:
1<VirtualHost *:80>
2 ServerAdmin subdomain@domain.tld
3
4 # Logging
5 # Rename these if you have or own scheme or remove them to log to the default files
6 LogLevel warn
7 ErrorLog ${APACHE_LOG_DIR}/default_redirect_error.log
8 CustomLog ${APACHE_LOG_DIR}/default_redirect_access.log combined
9
10 # Redirect to https://subdomain.domain.tld/
11 RewriteEngine on
12 RewriteRule "^/?(.*)" "https://subdomain.domain.tld/$1" [L,R,NE]
13</VirtualHost>
14
15# HTTPS
16<IfModule mod_ssl.c>
17<VirtualHost *:443>
18 ServerAdmin subdomain@domain.tld
19
20 # Logging
21 # Rename these if you have or own scheme or remove them to log to the default files
22 LogLevel warn
23 ErrorLog ${APACHE_LOG_DIR}/default_redirect_error.log
24 CustomLog ${APACHE_LOG_DIR}/default_redirect_access.log combined
25
26 # SSL Stuff Goes here
27 # I'm not completely sure this entire virtual host is necessary, but I decided to leave it
28
29 # Redirect to https://subdomain.domain.tld/
30 RewriteEngine on
31 RewriteRule "^/?(.*)" "https://subdomain.domain.tld/$1" [L,R,NE]
32</VirtualHost>
33</IfModule>
I was having problems at first because I wasn’t even using 000-default.conf
as a name, just the domain name.
If Apache is configured to use sites-available
and sites-enabled
it loads them alphabetically (I guess?).
Any way the first virtual host on the first config file loaded is the “default” one.
I was still having problems though, and even though I left directives like <DocumentRoot "/var/www/...">
and <ServerAlias domain.tld>
in there what finally fixed redirecting from the root domain to the subdomain was changing <VirtualHost *:*>
to <VirtualHost *:80>
.
This was throwing me off because the line is on the Apache website but doesn’t produce the result I thought it would: catching everything that was not port 443 or the other virtual hosts.
This is made clear if you run apachectl -S
, which prints the current configuration, and is great for debugging the virtual hosts because it lists them in order of precedence.