We help IT Professionals succeed at work.

301 redirect of a subdomain in Apache

Medium Priority
433 Views
Last Modified: 2012-05-11
I'm redirecting a subdomain in .htaccess this way:

    RewriteCond %{HTTP_HOST}        ^subdomain\.domain\.com
    RewriteRule ^$                 http://www.domain.com/en/keyword       [R=301,L]

On the first look, this works fine, but not entirely.

http://subdomain.domain.com/ gets redirected to http://www.domain.com/en/keyword

http://subdomain.domain.com/en/keyword does not get redirected at all!

I need a solution that will redirects all URLs of a specific subdomain to a single page.



Comment
Watch Question

dMa

Author

Commented:
Increased points to 500.
Top Expert 2015

Commented:
Easiest is to make virtual host for sub-domain and add a single redirect there.
CERTIFIED EXPERT
Top Expert 2004

Commented:
Can you turn on your RewriteLog?  If so, set the level to 9 and post the log for a single browsing attempt to a URL that does not forward.
Cloud/Infrastructure Solutions Architect
CERTIFIED EXPERT
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Commented:
Or, even shorter than mwecomputers' four config lines, you can create a subdomain virtual host in Apache, and then just include this one line:

Redirect 301 / http://server.com/subdirectory/
CERTIFIED EXPERT
Top Expert 2004

Commented:
In reference to mwecomputers' suggestion:

1) the [NC] flag may be important for you.  Make sure it is in your rule.
2) the rule highlights what I missed: the resource detection.  The difference being that you want all requests to go to a single page, so alter the rule as follows:

RewriteCond %{HTTP_HOST} ^subdomain\.domain\.com$ [NC]
RewriteRule .* http://www.domain.com/en/keyword [R=301,L]

Open in new window


As far the recommendation for a separate virtual host, it will work (indeed, my preferred method) if you have access to the server's config file.  Your question asked only about .htaccess, which means mod_rewrite is probably your best bet.
Your RewriteRule specifically states that it should only redirect where there is NOTHING after the HOST by specifying ^$:

RewriteCond %{HTTP_HOST} ^subdomain\.domain\.com
RewriteRule ^$ http://www.domain.com/en/keyword [R=301,L]

I think what you WANTED is:

RewriteCond %{HTTP_HOST} ^subdomain\.domain\.com
RewriteRule .* http://www.domain.com/en/keyword [R=301,L]

This will effectively redirect WITH or WITHOUT a path following the HOST.
dMa

Author

Commented:
Several correct answers, but mwecomputers was first.
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.