How To Redirect in Nginx all Domain Name Versions to https://www

| Servers | 2 seen

As you might already know search engines (Google) sees and as two separate domain names. If you are not using 301 redirects (www to non-www or vice verse)you might get penalized for duplicate content. 

In Ngnix, there is a simple solution how to make such redirect happen, see: Ngnix Redirect To WWW

Now, things get a bit complicated when https versions are involved. See: Linode: How To Secure Nginx with Let's Encrypt on Ubuntu 12.04

Once your website has https enabled, technically speaking you might be dealing with for different domain names:


What we are looking is to redirect all versions to one, I prefer the version with https://www, here is how to achieve that with Nginx server blocks.

Assuming you have already configured server blocks pointing your domain name to https://www open your server config:

sudo nano /opt/etc/nginx/sites-available/

And at the end of the code add:

  listen 80;
  return 301 https://$server_name$request_uri;
  listen 443;
  return 301 https://www.$server_name$request_uri;

Now, restart Nginx

sudo /etc/init.d/nginx restart

Hope it helps!