Nginx 301 redirect between non-www and www

Well… I would like my domain with no-www to be the only domain of my website shown in the Address Bar but I don’t want other people who type www.asd.as trying to visit my website but returns a 404 or “could not connect to the server” error.

I know that there’s a way to redirect the address and could be more SEO friendly which called “301 redirect”.

But I’m not sure how to do this with my Nginx web server, so I searched on Google to find the solution.

There are many method produce the same result. I choose the most easy and code-clear way and note down the code of Nginx configuration file below to remind me because I may have to do this again in the future.

 

www to non-www

server {
listen 80;
server_name asd.as;
#rest configuration here
}


server {
server_name www.asd.as;
rewrite ^/(.*)$ http://asd.as/$1 permanent;
}

non-www to www

server {
listen 80;
server_name www.example.com;
#rest configuration here
}


server {
server_name example.com;
rewrite ^/(.*)$ http://www.example.com/$1 permanent;
}

Leave a Reply

Your email address will not be published. Required fields are marked *