yoda
yoda

Reputation: 10981

apache - redirect subdomain to another domain

I need to redirect every subdomain into the domain it belongs changing the subdomain name into a parameter using mod_rewrite, and I'm not sure how. Also, I need to "reindex" the parameters so that the subdomain name becames the first parameter of the uri and the other parameters of the uri follow it by their own order. Something like this

category.domain.com/search/flowers

to

domain.com/category/search/flowers

Any thoughts on how to achieve this using mod_rewrite?

Cheers!

Upvotes: 4

Views: 8835

Answers (1)

bradym
bradym

Reputation: 4961

You can do this with one VirtualHost for all of the subdomains:

<VirtualHost *:80>
    ServerName category.domain.com
    ServerAlias foo.domain.com bar.domain.com

    RewriteEngine On
    RewriteCond %{HTTP_HOST} (.*).domain.com
    RewriteRule (.*) http://domain.com/%1$1 [R=301,QSA,L]
</VirtualHost>

For it to work properly, you must have something set as the ServerName, so just choose one and list the rest of your subdomains on the ServerAlias line.

You can have multiple ServerAlias lines, so you could break them into multiple lines for readability if you have a large number of subdomains.

In the RewriteRule, the %1 matches the first matched pattern in preceding RewriteCond lines.

Upvotes: 11

Related Questions