ngnix redirect non www to www

if you want to redirect non www to www domain you need to add one more serverblock at the top of your nginx config file as beloww

server {  
        listen 80;
        server_name techtrekking.net;
        # $scheme will get the http protocol
        return 301 $scheme://www.techtrekking.net$request_uri;
}

This works for normal website as well as ghost blog.
For example if you type techtrekking.net or www.techtrekking.net it will get redirected to www.techtrekking.net.

Sample server block. THis serves following purpose

  • redirect non www to www
  • add blog in subfolder /blog
server {  
        listen 80;
        server_name yoursite.com;
        # $scheme will get the http protocol
        return 301 $scheme://www.yoursite.com$request_uri;
}

server {  
        listen 80;
        listen [::]:80;

        root /var/www/html;

        index index.html index.htm index.nginx-debian.html;

        server_name techtrekking.com www.techtrekking.com;

        location / {
                proxy_pass http://yoursite:3000;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
        }

        location /blog {
                proxy_pass http://yoursite:3100;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;

        }


        location ~ /.well-known {
                allow all;
        }

}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.