Redirecting non-www to www in Nginx

July 13, 2014 69.2k views

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

5 Answers

Edit your virtualhost file and replace with and add this at the top:

server {
    listen 80;

    return 301$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;
         return 301 $scheme://$request_uri;
    server {
         listen 80 default_server;
         listen [::]:80 default_server ipv6only=on;
         root /var/www/;
         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 it goes to BUT it doesn’t load the site but error message:

    “Server not found” “Browser can’t find the server at

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

  • Hello,

    How about server_name; were will redirect to 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:

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.