How do I make a mod_rewrite rule that uses the sub-domain name to rewrite the URL?

What I want to do is something like this:

Forward requests FROM http://agency1.company.com TO: https://appname.company.com/appname/login.jsp?agencyName=agency1

It doesn't need to be a live proxy; It can just be a meta-refresh type of thing or a basic URL forward. Seems like this would be a common scenerio but I can't find an example on the internet. Lots of examples on the net of a URI rewrite but not many concerning a full URL rewrite (as I am trying to do above).


For this you can use Back-references.

RewriteEngine On
RewriteCond %{HTTP_HOST} ([^\.]+)\.domain\.com  [NC]
RewriteRule ^(.*)$ https://appname.company.com/appname/login.jsp?agencyName=%1 [R=301,L]

However, note this will end up redirecting again once the 301 is followed, IF the redir is to happen on HTTP only use the following block.

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ([^\.]+)\.domain\.com  [NC]
RewriteRule ^(.*)$ https://appname.company.com/appname/login.jsp?agencyName=%1 [R=301,L]

%1 refers to the first regex "capture" in the RewriteCond line, if you were to utilize mutliple points %2 and so on would become available.

  • That worked although I discovered that if the URL has a space in it, that the URL in the rewrite rule has to be quoted. – djangofan Apr 25 '11 at 20:22
  • In those cases wrapping the rule in quotes ("") often works, not sure if the %1 back ref works in those quotes though, will need some experimentation – Oneiroi Apr 25 '11 at 20:27
  • Also, doing it this way for SSL requires that I need to have a different SSL cert for each subdomain (wildcard cert of course). This explains why this rewrite method is not so common and I probably shouldn't have tried going down this path. A URI rewrite method would work better: using only 1 certificate. – djangofan Apr 26 '11 at 19:29

You can use RewriteCond on the HTTP_HOST value to do this. There's a couple examples of this usage in the Apache URL Rewriting Guide. You would do something like this:

RewriteEngine on
RewriteCond   %{HTTP_HOST}                 ^[^.]+\.company\.com$
RewriteRule (.*) https://appname.company.com/$1?agencyName=%1 [R,L,QSA]

This is untested, and might not work as is, but should point you in the right direction.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.