Help needed with nginx rewrite rules

So I've started playing around with nginx and wow did it decrease the load on my VPS compared to Apache2. I've come across one problem I can't solve with it though.

I have two domains - foo.com and bar.com. I want all requests for bar.com to redirect permanently to foo.com. I've got the following in my nginx.conf, but when I try to hit bar.com nginx complains about too many redirects and doesn't load foo.com.


server {
server_name .foo.com;
rewrite ^ http://www.bar.com$request_uri? permanent;
}

Am I missing a step somewhere?

Wait, you want people hitting bar.com to go to foo.com? I think your config has it backwards. The end result of the rewrite should be the destination.

server {
server_name .bar.com;
rewrite ^ http://foo.com$request_uri? permanent;
}

server {
server_name foo.com foo.com;
etc, etc, etc
}

That gave too many redirect errors as well. ngix can't do nested/complex conditions, right? I think it's complaining because I've got both domains on the same server being served by nginx. Would something like the following work or am I over thinking this?

set $my_var 0;
if ($host = 'foo.com') {
set $my_var 1;
}
if ($host = 'bar.com') {
set $my_var 1;
}
if ($my_var = 1) {
rewrite ^/(.*)$ http://foo.com/$1 permanent;
}

This should be a trivial thing for any webserver to do. I could swear that the config in my post should work, but maybe I'm missing something. If conditionals are to be avoided in the server config on general principle, just because of how inefficient they are, though the appeal of "well, at least it WORKS" can be strong.

You might try adding rewrite_log on to the config blocks. That should dump some notice level stuff to your error log, which might point you at something we're not seeing.

I just installed nginx from epel on a test server I have access to, and setup a hostname to point at one of its IPs. With a simple

server {
server_name test.example.com;
rewrite ^ http://anotherdomain.example.com$request_uri? permanent;
}

That worked, but I was redirecting to another host.

Let me try something setup on the same IP / server.

Yeah, a second conf file for a different hostname redirected correctly. I just copied the default.conf, changed the location to a new path, and put a simple index.html in there.

server {

...
server_name second-hostname.example.com;

location / {
root /var/www/nginx/second-hostname;
index index.html index.htm;
}
...
}

Yeesh, sorry for the late thank you for the help with this (work has been kicking my ass the past month or so), but my problem ended up being solved with your very first reply. It wasn't working for me at first because I was trying to do everything in one domain file in /etc/ngix/sites-available/. Once I created two separate files and symlinked them in /etc/nginx/sites-enabled/ I was good to go.

Thanks again for the help. My little VPS is much happier now!

Awesome, glad you got it worked out!