Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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).

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

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.

share|improve this answer
    
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
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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