Tips & Tricks Tips & Tricks How to redirect non-www versions of your website in nginx?

Short answer

You should serve your website on one, and only one FQDN. Whether you want the www or bare domain to be the one is up to you, but once you made your choice, redirect all other versions to it and stick to this choice.

server {
  listen 80;
  server_name www.example.net;

  # ... your config ...
}

server {
  listen 80;
  server_name example.net *.example.net;

  rewrite ^ http://www.example.net$request_uri permanent;
}

Details

For SEO purposes, having only one version of your pages is important. I don't believe duplicate content is as harmful as often advertised, but it won't do you any good, and it will be confusing to your users, so please, don't.

The same thing is true for HTTP vs HTTPS versions. If you can, serve everything via https and redirect the HTTP version to your page. You can use the same trick to do so

server {
  listen 80;
  server_name example.net *.example.net;

  rewrite ^ https://www.example.net$request_uri permanent;
}

Also, although it won't change a lot, make your redirects work with deep links (and refrain yourself from redirecting everything to the / path). It will allow, for example, to got to romain.dorgueil.net/blog when typing dorgueil.net/blog in a browser.

It will also prove useful on the day you wanna migrate your site from HTTP to HTTPS, as all links will keep working.

Share the love!

Liked this article? Please consider sharing it on your favorite network, it really helps me a lot!

You can also add your valuable insights by commenting below.