How to get hostname into rewriterule
The simple case suggested by Ladadadada works when the domain name is same between requested host and intended host:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=302,L]
However, an extra difficulty is that I also need to have http:// sub-domain.local
redirect to http:// sub-domain.net.au
- so using %{HTTP_HOST}
wouldn't be sufficient.
I had another look at some examples, and realised that the %1 back-reference seems to only apply to the RewriteCond immediately prior to RewriteRule.
I reordered things:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(.*)(.local|.net.au)$
RewriteRule ^(.*)$ https://%1.net.au$1 [R=302,L]
And the redirects work great
Related videos on Youtube
![HorusKol](https://i.stack.imgur.com/Skasm.jpg?s=256&g=1)
HorusKol
Updated on September 18, 2022Comments
-
HorusKol almost 2 years
We've got a few subdomains setup, and I want to simplify some apache configuration - particularly as these particular subdomains are volatile. Anyway, I'm trying to get a rewrite rule that include the host.
So far, I've got:
RewriteEngine On RewriteCond %{HTTP_HOST} ^(.*).net.au$ RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%1.net.au$1 [R=302,L]
This is based on https://stackoverflow.com/questions/3634101/url-rewriting-for-different-protocols-in-htaccess and http://httpd.apache.org/docs/2.4/rewrite/vhosts.html
However, the pattern in the first condition isn't written into the rewritten address, and I end up being sent to .net.au/wherever (wouldn't let me post with the https in front) - have I missed something?
Running apache 2.4 on Ubuntu 14.04
-
Ladadadada over 9 yearsThat looks needlessly complicated. Why not just Redirect to
https://%{HTTP_HOST}$1
and get rid of the first RewriteCond? -
HorusKol over 9 years@Ladadadada because I didn't know you could do that - but after re-reading the manual
the Substitution string can include
server-variables as in rule condition test-strings (%{VARNAME})
-
HorusKol over 9 years@JennyD could you link to where my question is answered there?
-