Nginx Redirect HTTP to HTTPS and non-WWW to WWW

Here is my solution to do the redirection.

Say, I have a web site. I host it with SSL.

I want all these three type of host go to the same Unique Internet Address.

From:

  • http://example.com/
  • http://www.example.com/
  • https://example.com/

To:

  • https://www.example.com/

There are some requirement:

  • Nginx v1.8
  • SSL Certificate is issued for both  example.com and www.example.com

I have the website config file in /etc/nginx/sites-available/example.com

Add following into it.

server {
listen         80;
server_name    www.example.com  example.com;
return         301 https://www.example.com$request_uri;
}

server {
listen         443 ssl;
server_name     example.com;
return         301 https://www.example.com$request_uri;
ssl_certificate /etc/ssl/ssl.key/ssl-bundle.crt;
ssl_certificate_key /etc/ssl/ssl.key/www.example.com.sha256.key;
}