301 redirect with Nginx? Server_name is localhost

Posted December 15, 2014 14.2k views

Probably an obvious question, but I’m new to this stuff…

I’m trying to use a 301 redirect to get to resolve to - currently, a user can open two different sessions on www and non-www, which we’d like to prevent. I found this very helpful Stackoverflow post:

But when I open up my default file in etc/nginx/sites-available, the server_name is localhost, not How do I deal with this situation?

Any help greatly appreciated.

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Submit an Answer
2 answers

The server_name directive is set to localhost by default but you can replace it with your domain name and it would work just as well. The reason it works right now is because there’s only one server block so nginx defaults to it even if you’re browsing to and not http://localhost.

  • OK, I added a separate server block that looks like this:

    server {
    listen 80;
    return 301$request

    And restarted nginx (sudo service nginx restart), but it’s still happening - I can have two tabs open to different sessions at and Do I need to delete the www CNAME record from my DNS here on Digital Ocean now?

  • Where did you add that server block? Can you also post the existing server block for

    DNS maps a hostname (e.g. to an IP address. It doesn’t handle redirects so you’ll need both a DNS record that points to your droplet’s IP address and nginx to redirect requests from to

  • I sshed into our ip as root and added it to etc/nginx/sites-available/default. Prior to my changing it, the server block looked like this:

    server {
        listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;
        root /usr/share/nginx/html;
        index index.html index.htm;
        server_name localhost;
        location / {
            try_files $uri $uri/ = 404;

    I changed the server_name in that block to rather than localhost, and then added the other block I pasted above. Not sure what the ipv6only=on line is about, since we’re not using ipv6 as far as I know.

    Thanks very much for your help. I assume I’m missing something obvious here.