Redirecting from mysite.com to www.mysite.com

On my local dev machine, here is my /etc/hosts file:

127.0.0.1 localhost mysite.com www.mysite.com

And in my Nginx config file I have:

server {
server_name mysite.com;
rewrite ^/(.*) http://www.mysite.com/$1 permanent;
}

But when I want to access mysite.com or www.mysite.com I get the
following error message:

Firefox has detected that the server is redirecting the request for
this address in a way that will never complete.

What could possibly go wrong?

Do you have this server block also defined?

server {
server_name www.mysite.com;
^^^^
}

You’re probably falling on an infinite loop.

Hmmm that’s getting strange:

In my other server block, I had: server_name _;

And I got this infinite loop.

So I have now hardcoded the server name as: server_name www.mysite.com;

Now I don’t get the infinite loop, but the rewriting of mysite.com
www.mysite.com doesn’t happen.

Thomas a écrit :

Do I need to explicitly create a server_name for each domain I am
handling? I would like to be able to create an unattended config file
that I won’t “ever” touch again.

My guess is your server block with “site.com” on the server name is
defined
before the other one with the name “_”.
The first server block found is the one used when no Host matches any
server
name (unless there’s a “default” param for a server).
http://wiki.codemongers.com/NginxHttpCoreModule#listen

UPDATE: sorry, I had forgotten to add mysite.com to /etc/hosts, so now
redirection works.

But if I put server_name _; back then I get the loop.

I tried using this trick: Catchall domain with 0.6.30 - NGINX - Ruby-Forum

with server_name_in_redirect off;

but I still get the infinite loop.

Do I need to explicitly create a server_name for each domain I am
handling? I would like to be able to create an unattended config file
that I won’t “ever” touch again.