How to Redirect HTTP Traffic to HTTPS in Nginx and Apache

In this tutorial, we will show you how to redirect HTTP traffic to HTTPS in Nginx and Apache. You should always use HTTPS instead of HTTP to protect your website, even if it doesn’t handle sensitive communications. The main reasons to use HTTPS are:

Security – this is the main and most important reason to use HTTPS, all communications between the visitor’s browser and the website are encrypted.

Redirect HTTP to HTTPS with Nginx

We need to create three server blocks, one for HTTP, one for HTTPS NON-WWW and one for HTTPS WWW versions of the site. The first server block will redirect all visitors entering the site via HTTP to HTTPS and the two other blocks will redirect visitors entering the site via WWW to NON-WWW or vice-versa.

To redirect all HTTP and HTTPS NON-WWW traffic to HTTPS WWW, use the following code: