How to Redirect Non-www Traffic to WWW on Nginx

Running Nginx web server to speed up one’s blog is good, however, configuring optimal settings should be one’s goal. What is the best way to configure Nginx redirect to combine both www and non-www traffic?

Students who want to learn how to configure Nginx webserver to redirect all traffic to WWW domain can follow the steps below to do that.  The reasons webmasters and blog owners redirect all traffic to one domain is to avoid duplicate content.

When it comes to web traffic, computers and other bots see and as separate domains even though they’re one. To avoid this conflict, you must enable redirects.

You redirect to and vice versa. So typing either will take you to one bring redirected to.

That’s the simple explanation. This is known as 301 redirect in web lingo.

To get this configured with Nginx webserver, open Nginx configuration page and add the line below and save it. Search this website to find answers and tutorials on Nginx that show where Nginx default settings pages are stored.

Find the server block, then add the highlighted line and save the file.

server {
        server_name _;
        return 301 $scheme://$request_uri;

After updating the configuration file with the content above, restart nginx and you’re done. Every time someone visits your site, they’ll always be redirect to

You can switch it to go to instead by removing the www from the content above.

That’s it! Hope this helps.

If you know of any other way to do that, please add to this answer.. we appreciate your help.

Leave a Reply

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

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