Psychz - John
Votes: 0Posted On: Jun 06, 2017 03:20:53
Nginx is one of the world's most prominent web server solutions. It is an open source solution that provides high performance, concurrency and low memory consumption. Nginx also comes with a paid version called Nginx Plus.
Why redirect HTTP to HTTPS?
HTTP is the protocol with which the communication occurs between the web server and browser. HTTPS is another protocol used which is more secure than HTTP. The "S" stands for "secure". It uses a protocol such as SSL(Secure Sockets Layer) to encrypt data between web server and browser. Hence, it is very useful to redirect all HTTP data to HTTPS port.
How to redirect HTTP to HTTPS?
Prerequisites
1. Setup HTTPS on Nginx - Firstly, you need to set up HTTPS on Nginx. For this, you will have to generate and private key and CSR(Certificate Signing Request) key.
2. After you have generated the key, the next step is to acquire the SSL certificate from a Certificate Authority.
3. The third step is to configure Nginx server block by adding the SSL certificate and key. Reload the configuration to save the changes.
Redirecting all HTTP traffic to HTTPS
server {
listen 80 default_server;
listen [::]:80 default_server;
return 301 https://$host$request_uri;
}
This a very general configuration that will redirect all the hostnames on the server.
Let us go through the code line by line.
1. server - The name of the block in which the code is written.
2. listen 80 default_server; - The port number 80 is the "http" port and the default_server is the hostname of your server. This is to redirect all IPv4 HTTP packets incident on your server.
3. listen [::]:80 default_server; - This line functions same as above but for all IPv6 HTTP traffic.
4. return 301 https://$host$request_uri; - the code "301" is used to redirect the traffic. "https://$host$request_uri;" is the target at which all the traffic will be redirected to.
Here is an example for your reference.
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name test.com www.test.com;
return 301 https://$server_name$request_uri;
}
Here, all the HTTP traffic from "test.com" and "www.test.com" are redirected to HTTPS.