301 redirect with Nginx? Server_name is localhost

December 15, 2014 11.4k views

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

I’m trying to use a 301 redirect to get www.ourapp.com to resolve to ourapp.com - 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: http://stackoverflow.com/questions/7947030/nginx-no-www-to-www-and-www-to-no-www

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

Any help greatly appreciated.

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 http://yourapp.com and not http://localhost.

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

    server {
    listen 80;
    servername www.streamfeed.com;
    return 301 http://streamfeed.com$request

    And restarted nginx (sudo service nginx restart), but it’s still happening - I can have two tabs open to different sessions at streamfeed.com and www.streamfeed.com. 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 streamfeed.com?

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

  • 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 streamfeed.com 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.

Awesome, thank you!

Have another answer? Share your knowledge.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!