Question

Redirecting non-www to www in Nginx

Posted July 13, 2014 87.4k views

I have successfully installed LEMP stack in Ubuntu 14 and running a phpBB forum. But the problem is that when I enter www.mydomain.com it shows a network error. Somebody please help me.

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.

×
4 answers

Edit your virtualhost file and replace yourdomain.com with www.yourdomain.com and add this at the top:

server {
    listen 80;
    server_name yourdomain.com;

    return 301 http://www.yourdomain.com$request_uri;
}

Restart nginx:

sudo service nginx restart

Finally, add a CNAME record with the name of “www” and the hostname of “@”.

  • hi, I have the exact same problem but it’s still unsolved. This is my virtualhost file setting:

    server {
         listen 80;
         server_name website.com;
         return 301 $scheme://www.website.com$request_uri;
    }
    
    server {
         listen 80 default_server;
         listen [::]:80 default_server ipv6only=on;
         root /var/www/website.com/html;
         server_name www.website.com;
    
         the rest of the code settings....
    
    }
    
    

    I then restarted nginx with

    sudo service nginx restart
    

    I also added CNAME:

    www with @

    • with @

    So now, when I type website.com it goes to www.website.com BUT it doesn’t load the site but error message:

    “Server not found” “Browser can’t find the server at www.website.com.

    Is there anything I’m missing here? Thank you in advance!!

  • Hello,

    How about server_name www.domain.com domain.com; were www.mydomain.com will redirect to domain.com? is it not good for seo? i use wordpress

Thanks Kamal Nasser. Now it is working perfect.

I followed your guideline. But still it is not redirecting. Do I need to wait few hours for adding CNAME to take effect?

P.S.: vhost config: http://tny.cz/8fa87c05

Is this a PTR records issue? I set it to the same as hostname.

$hostname
phpBB

Do I need to set PTR records to something different from above?

Submit an Answer