In an nginx server block:

server {
  listen       80;
  server_name foo.com bar.com car.com;


How do I redirect bar.com/site and only bar.com/site to bar.com/ - the other hosts should remain unaffected. So foo.com/site and car.com/site should work as normal.

if ($host ~* ^bar.com$) {
    rewrite ^/site(.*)$ /;

or different server locations with include of shared zones

  • I like "different server locations with include of shared zones" better. Nginx docs say if is evil and recommend avoiding it when possible. (But rewrite is one of the directives they say is safe inside if blocks, so this answer is perfectly correct.) – pjmorse Oct 18 '12 at 13:24
  • So obvious! Thanks :) I've just added a permanent so its a redirect rather than a rewrite. – jaygooby Oct 18 '12 at 13:40
  • Yep, if its evil. Check all requests not the best practice for high-load servers. More faster - takes 3 servers like: server {server_name foo.com; include someconf.conf;} – unlo Oct 18 '12 at 13:43
  • Yep, well aware of the "if is evil" :) – jaygooby Oct 18 '12 at 13:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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