Redirecting non-www to www in Nginx

Posted July 13, 2014 96.9k 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.

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
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

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:

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?