Apache mod_rewrite for wildcard subdomains

I want to allow dynamic subdomains, and am trying to use a staging subdomain for testing.

I want to make the following work, without changing the web browser address bar.

Start with:

http://foo.www-staging.domain.tld/SomePage?name=val

Should become:

http://www-staging.domain.tld/SomePage? … o&name=val">http://www-staging.domain.tld/SomePage?subdomain=foo&name=val

I have gotten the DNS set up to accomplish this, and have gotten the VirtualHost setup to serve correctly. My problem is figuring out the correct code in the .htaccess file. I have also tried using the ENV flag (e.g. [E=subdomain:%1]), but have had no success.

I have been able to get the above URL rewriting to work by forcing it in the browser, but all of my attempts to keep it under the covers of the browser address bar causes infinite rewriting.

Any suggestions?

3 Replies

Do you have a RewriteCond checking if the HTTP hostname is www-staging.domain.tld, so that mod_rewrite doesn't loop?

Something like

RewriteCond %{HTTP_HOST} !^www-staging

Here is what I have so far, and your addition did not seem to help. I still am redirected.

RewriteCond %{HTTP_HOST} ^([^.]+)\.www-staging\.domain\.tld [NC]
RewriteRule ^(.*)$ http://www-staging.domain.tld/$1?subdomain=%1 [NS,QSA,E=subdomain:%1]

Whoops. I just re-read your question more carefully and realized you're rewriting internally, not doing a HTTP redirect, so my suggestion above is totally useless. Sorry.

Have you tried doing something like

RewriteCond %{QUERY_STRING} !subdomain=

?

Edit: Reading your second post, it seems like you are doing a HTTP redirect (the external URL in your RewriteRule). Is this what you want to do?

Reply

Please enter an answer
Tips:

You can mention users to notify them: @username

You can use Markdown to format your question. For more examples see the Markdown Cheatsheet.

> I’m a blockquote.

I’m a blockquote.

[I'm a link] (https://www.google.com)

I'm a link

**I am bold** I am bold

*I am italicized* I am italicized

Community Code of Conduct