How To Redirect Http To Https In Nginx

NGINX is one of the most flexible high-performance website servers out there. If you’re still serving up unencrypted HTTP traffic, you’re doing your users a disservice. Set up a cheap (or free) certificate and start using NGINX lớn redirect HTTP khổng lồ HTTPS!

In this tutorial, you’re going to lớn learn how to create a self-signed certificate and automatically redirect all HTTP traffic to lớn HTTPS, so your traffic always remains encrypted.

Bạn đang xem: How to redirect http to https in nginx


To follow along with this tutorial, be sure you have the following:

A Linux server – This tutorial uses Ubuntu 20.04 LTS, but you can perform the same steps with any other Linux distribution.A user tài khoản with sudo privileges.

Installing OpenSSL

Before you begin activating NGINX to lớn Redirect HTTP khổng lồ HTTPS traffic you must first have an SSL certificate installed on your website server. The certificate will be used to encrypt all traffic send & received over HTTPS. Lớn create a self-signed certificate, though, you’re going to need OpenSSL, so let’s first install it.

On your NGINX website server:

1. Change lớn the /usr/local/src directory. This directory will be where you’ll install OpenSSL. Cd /usr/local/src

cd /usr/local/src
2. Tải về the OpenSSL tarball using wget.

Related: How to download Files with Python Wget

sudo wget

Downloading OpenSSL
3. Extract the files from OpenSSL tarball.

sudo tar -xf OpenSSL-1.1.1g.tar.gz
4. Configure OpenSSL to links the shared libraries that the executable file needs when it is executed.

sudo ./config -Wl,--enable-new-dtags,-rpath,"$(LIBRPATH)"

Extract và Configure OpenSSL
5. Compile and install OpenSSL by running the following commands.

sudo makesudo make install

Generating a Self-Signed Certificate

Now that you have OpenSSL installed, you must have a certificate that HTTP will use. For this tutorial, you’ll be creating a self-signed certificate.

Self-signed certificates are not signed by trusted certificate authorities and shouldn’t be used in production; they should be used just for testing purposes. If you need an SSL certificate for production, you can get it from a Certificate Authority such as Let’s Encrypt.

1. Create a directory called local_ssl with a configuration tệp tin called open_ssl.conf inside. This file will be used as a certificate request to generate a self-signed certificate.

mkdir local_sslcd local_ssltouch open_ssl.conf
2. Edit the open_ssl.conf configuration file created in step six and copy/paste the following content into it. This tệp tin contains the certificate issuer’s details and other details such as your domain name, in this case, your details since it is a self-signed certificate và you are acting as the Certificate Authority (CA).

distinguished_name = req_distinguished_namex509_extensions = v3_reqprompt = noC = //Country code, any country code, 2 letters e.g USST = //State, any stateL = //City, any cityO = //Organisation name, can be anything you wantOU = //Department, can be anything you wantCN = //Certificate Issuer, can be anything you wantkeyUsage = keyEncipherment, dataEnciphermentextendedKeyUsage = serverAuthsubjectAltName =
alt_namesDNS.1 = //Domain name 1DNS.2 = //Domanin name 2
3. Now generate the SSL certificate with the OpenSSL command. The following command will generate a certificate and a key that will be used lớn sign the certificate.

req– Tells OpenSSL lớn generate a certificate request.nodes– Tells OpenSSL to skip the option that lets you protect the private key with a passphrase.days– Specifies the certificate validity period in days.newkey rsa: 2048– Generates a new private key using the RSA algorithm with a key length of 2048 bits.keyout– Specifies where you want the private key that will be created to lớn be stored.out– Specifies where you want the certificate that will be created to lớn be stored.

Xem thêm: Giảm Kích Thước Ảnh Bằng Photoshop Dễ Dàng Nhất, Cách Chỉnh Kích Thước Ảnh Trong Photoshop

config– Specifies the path khổng lồ the configuration file.

openssl req -x509 -nodes -days 1024 -newkey rsa:2048 -keyout localhost.key -out localhost.crt -config open_ssl.conf -extensions "v3_req"

Generate SSL Certificate

Configuring NGINX lớn Use a Certificate

You now have a certificate, let’s now configure NGINX to lớn use it.

1. Copy the certificate & key khổng lồ the /etc/ssl/certs & /etc/ssl/private directories, as shown below. You must vị this so that Ubuntu can find them when necessary.

sudo cp localhost.crt /etc/ssl/certs/localhost.crtsudo cp localhost.key /etc/ssl/private/localhost.key
2. Edit the NGINX configuration file at /etc/nginx/sites-enabled/default and copy/paste the following code in the vps block of your NGINX configuration file. The lines below ensure NGINX listens on port 443, binds the certificate previously created khổng lồ NGINX, and enables TLS v1.2, and 1.3.

listen 443 ssl;listen <::>:443 ssl;ssl_certificate /etc/ssl/certs/localhost.crt;ssl_certificate_key /etc/ssl/private/localhost.key;ssl_protocols TLSv1.2 TLSv1.3;
3. Next, restart NGINX to force the webserver khổng lồ read the new configuration file modified in step 10.

systemctl restart Nginx
4. Mở cửa a website browser on the Linux host and navigate to http://localhost. The connection to the webserver should fail, as you see below.

Accessing Insecure Version of the Site

5. Now, navigate khổng lồ https://localhost, & you will see the mặc định NGINX page come up.

View https version of local host

Trusting the Self-Signed Certificate

Even though the site renders using HTTPS, the browser still says it is not secured. The browser still displays a Not secure label because the browser doesn’t have the self-signed certificate’s public key to trust it.

For the browser to lớn trust the self-signed certificate, the browser must have access lớn the certificate’s public key. To vị that, you will need the certutil utility which comes with the libnss3-tools package.

1. First, install the libnss3-tools package by running the following commands:

sudo apt-get updatesudo apt-get install libnss3-tools
2. After the installation is complete, navigate to lớn the thư mục where the certificate file is (in this case, /etc/ssl/certs) & run the following command to add the certificate.

certutil -d sql:$HOME/.pki/nssdb -A -t "CT,c,c" -n "localhost" -i localhost.crt
3. Finally, close & reopen the browser. You should now see that the browser trusts the certificate.

Showing Secure Connection

Using NGINX to redirect HTTP lớn HTTPS

You should now have a certificate created and bound to lớn NGINX with NGINX serving up traffic on HTTPS. It’s now time to lớn redirect all HTTP traffic to lớn HTTPS automatically.

In the NGINX configuration file, you can configure HTTP to lớn HTTPS redirection in a couple of different ways. You can set redirection up on a site-by-site basis or all sites at once. Let’s go through each method.

After making changes khổng lồ the NGINX configuration file, always ensure you restart NGINX (systemctl restart Nginx).

If you have more than one site on your web server, you can selectively pick which one you’d lượt thích to redirect HTTP lớn HTTPS traffic on. To vày that, configure the NGINX configuration file as shown below.

The snippet below configures NGINX lớn listen on port 80 (HTTP) and immediately send a redirect request (HTTP/301) lớn the user using the same $request_uri that they requested but using HTTPS.

server listen 80; listen <::>:80; server_name ; return 301 https://$request_uri;
If you navigate khổng lồ http://localhost, you’ll now see that you’re automatically redirected to that same page only encrypted with HTTPS.

If you’d like to redirect all HTTP traffic destined for your webserver khổng lồ HTTPS, replace the server_name attribute from the vps name to lớn simply _. The _ value is lượt thích a wildcard for all incoming hostnames.

You’ll also see the redirection statement (return 301) has changed to https://$host$request_uri indicating that you want khổng lồ redirect whichever hostname is typed in as the $host variable returns the domain name of a request.

Xem thêm: Tuyển Dụng, Tìm Việc Bán Hàng Qua Mạng, 6 Việc Làm Phù Hợp Nhân Viên Bán Hàng Online

server listen 80; listen <::>:80; server_name _; return 301 https://$host$request_uri;


You should now have to lớn use NGINX khổng lồ redirect HTTP to HTTPS solution set up & working. Navigate to lớn your web server on HTTP & notice how it automatically redirects you!

What areas do you see that would benefit the most from this approach?

NGINX to lớn Redirect HTTP to HTTPS

Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

Explore ATA Guidebooks

More from ATA Learning và Partners

Continue reading with these similar tutorials



Don"t be left behind with the ATA Learning Newsletter!

Looks like you're offline!