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.

I have configured my first nginx server, and I have to redirect subdomain1.domain.com, subdomain2.domain.com and a few more to domain.com

I searched a lot about rewriting in nginx but couldn't find anything that works. Thanks!

share|improve this question
    
If you are just trying to rewrite everything to the main domain, I'd favour: server{server_name subdomain1.domain.com subdomain2.domain.com; rewrite ^ http://domain.com permanent;} - you can change http://domain.com to http://domain.com$request_uri to preserve the path. You can also use regex matching or a wildcard in the server_name (e.g. *.domain.com) if you have a significant number of subdomains. –  cyberx86 Feb 21 '12 at 17:58
    
Thanks, it worked like a charm. I'm going to dig deeper into nginx cause I really like it since I started working with it. –  Alex Feb 21 '12 at 18:08
    
Nginx is great, but it is important to not approach its configuration the 'Apache' way - especially for rewrites. If you are just starting with Nginx, their Wiki is a great resource (although, occasionally missing information). Definitely read IfIsEvil and Pitfalls. –  cyberx86 Feb 21 '12 at 18:16

1 Answer 1

up vote 1 down vote accepted

Nginx only knows about the (sub)domains that match a server_name in a server block. Requests for any other (sub)domain will end up in the 'default' server block, if you have one setup.

You, therefore need to create a new server block that will match the subdomains you are interested in.

server{
    server_name subdomain1.domain.com subdomain2.domain.com;
}

You can also use regex matching or a wildcard in the server_name (e.g. *.domain.com) if you have a significant number of subdomains.

Within that server block, add your rewrite (essentially amounting to, anything hitting these subdomains should be rewritten to my main domain).

rewrite ^ http://domain.com permanent;

Put it all together, and you get:

server{
    server_name subdomain1.domain.com subdomain2.domain.com;
    rewrite ^ http://domain.com permanent;
}

You can change http://domain.com to http://domain.com$request_uri to preserve the path.

share|improve this answer

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.