Nginx config: Redirect www requests to non-www
-
I switched over to Nginx from Apache and am using the SSL config here. This works great but I'd like to modify it so that all requests to www are redirected to non-www.
Can anyone help?
-
I'm not sure if you're using Cloudflare. If you do you can make a Pagerule that redirects any www. to the main URL. http://i.imgur.com/E10DLXE.png
If you just use Nginx, this should help you on your way. http://stackoverflow.com/questions/7947030/nginx-no-www-to-www-and-www-to-no-www
-
Sure thing. Navigate to your server config file (/etc/nginx/sites-availble/your_file) or wherever you keep it and add one more server block before your main server block.
Important: Don't use rewrite, as that's a common pitfall, as stated here
So with that said, to canonicalize your domain:
-www to no www:
server { server_name www.example.com return 301 $scheme://example.com$request_uri; }
To canonicalize your IP:
server { server_name your:ip:address:here; return 301 $scheme://example.com$request_uri; }
And then finally your main server block:
server { listen 80; server_name example.com; [...] }
-
Thanks for your help, these responses have been very useful. Also, if anyone is using Digital Ocean and stumbles upon this topic, I found a pretty good tutorial here.
-
@henrywright I kinda avoided quoting Digital Ocean as I found there guide a bit confusing.