Let's say I want to redirect from www.example.com to example.com and I want to do this using nginx. I looked around and did not see any good documentation on this so I figured I would ask and answer my own question.
Let's say I want to redirect from www.example.com to example.com and I want to do this using nginx. I looked around and did not see any good documentation on this so I figured I would ask and answer my own question.
I also looked at this on the Nginx wiki and other blogs and the best way performance wise is to do the following:
To redirect from www.example.com to example.com using nginx (version 1.0.12 at time of writing).
When requests come to example.com, no if statements are used for performance. And it uses $request_uri rather than having to create a $1 match which taxes the rewrite (see Nginx Common Pitfalls page).
Sources:
Please visit this question in SO: https://stackoverflow.com/a/11733363/846634
From the better answer:
Actually you don't even need a rewrite.
As my answer is getting more and more up votes but the above as well. You should never use a
rewrite
in this context. Why? Because nginx has to process and start a search. If you usereturn
(which should be available in any nginx version) it directly stops execution. This is preferred in any context.After some digging around and some missteps, here is the solution. The gotcha I ran into is to make sure to use "http://example.com$uri". Inserting a / in front of $uri results in a redirect to http://example.com//
To redirect to non-www, amend vhost file:
'Permanent' turns the redirect into a 301 redirection. After this code block, you can config the domain without www.
For redirecting non-www to www:
Thassit.
BTW, for full VPS setup using Nginx, check out the VPS Bible on my site, guvnr.com, and I hope that's handy!
This is what I use: