Configuring SSL with NGINX takes only several minutes. All you need to do is to save your SSL certificate and key files on the server and modify the NGINX conf file to refer to them.
When you purchase an SSL certificate, you must download the files that make up your SSL certificate.
That usually includes two files. In this tutorial, we will use two files,
Download both
The next step is to modify the Nginx config file to create an HTTPS server block and reference SSL certificate files within the new server block.
To maintain a canonical form of the URL, all noncanonical representations of the URL will redirect to the canonical URL format.
Our canonical URL will be
The below server block adds HTTPS support. It accepts
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
#Placeholder to include the ssl certificate and key
ssl_certificate_key /etc/nginx/certs/ssl_certificate.key;
location / {
proxy_pass http://127.0.0.1:3000/;
}
}
The server should have the SSL certificate installed to use SSL. We completed this step in step 1.
Ensure the paths to
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name www.example.com;
ssl_certificate /etc/nginx/certs/ssl_certificate.crt;
ssl_certificate_key /etc/nginx/certs/ssl_certificate.key;
location / {
proxy_pass http://127.0.0.1:3000/;
}
}
As I mentioned above, I redirect all the noncanonical URLs to the canonical format, which is
Redirects all non-ssl to
server {
listen 80 default_server;
listen [::]:80 default_server;
return 301 https://$host$request_uri;
}
Redirects
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com;
ssl_certificate /etc/nginx/certs/ssl_certificate.crt;
ssl_certificate_key /etc/nginx/certs/ssl_certificate.key;
return 301 https://www.example.com$request_uri;
}
After all the changes, the complete Nginx config file will look below.
server {
listen 80 default_server;
listen [::]:80 default_server;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com;
ssl_certificate /etc/nginx/certs/ssl_certificate.crt;
ssl_certificate_key /etc/nginx/certs/ssl_certificate.key;
return 301 https://www.example.com$request_uri;
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name www.example.com;
ssl_certificate /etc/nginx/certs/ssl_certificate.crt;
ssl_certificate_key /etc/nginx/certs/ssl_certificate.key;
location / {
proxy_pass http://127.0.0.1:3000/;
}
}
Now we have completed all the required changes to accommodate SSL. Finally, restart your Nginx server to make changes into effect.