Nginx

How To Redirect www To non-www And Vice Versa with Nginx

In this short tutorial I’ll show you how to make permanent redirect from a www URL to non-www and vice versa. I’ll assume that you have superuser privileges, sudo  or root access and Nginx already configured, as well as DNS records. More specifically, you need to have an A records for www.yourdomain.com  and yourdomain.com .

Redirect non-www to www

To redirect users from a plain, non-www domain to a www domain, you need to add this snippet in your Nginx domain configuration file:

Save your configuration and exit. Before restarting Nginx make sure to test your configuration:

You should have something like this as output:

Now when everything is checked you can restart Nginx:

Now, if you curl your plain domain, you should get a  301 Moved Permanently  response:

Redirect www to non-www

In the previous example you saw how to redirect users from a plain non-ww domain to a www domain. However, if you want to redirect from a www to a plain non-www domain you need to add following snippet in your domain configuration file:

After any change in Nginx configuration files you should test it for syntax errors:

And if you curl the www domain you should get same 301 Moved Permanently  response:

And that’s it. You have properly configured permanent redirect.

References:

NGINX 301 Redirects

Nginx rewrite non-www-prefixed domain to www-prefixed domain

Nginx config for www to non-www and non-www to www redirection

How To Redirect www to Non-www with Nginx on CentOS 7

Follow me

Mirza Pasic

Full Stack Developer at OLX
Web Developer. Geek. Systematic. Dreamer
Follow me

Published by

Mirza Pasic

Web Developer. Geek. Systematic. Dreamer

  • Kishore Pandey

    Hi,

    I really like your blog here. I added this in my Fav list.

    BTW how did you manage to create such a nice and clean looking website? Did you write a tutorial for the same somewhere?

  • Miguel Vieira

    Can you provide a solutions for a dynamic domain ie, redirect all traffic from non-www to www but for any domain?