Redirecting non-www to www in Nginx

July 13, 2014 41.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.

5 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

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.


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

Thanks Kamal Nasser. Now it is working perfect.

Have another answer? Share your knowledge.