This tutorial explains how to redirect HTTP requests to HTTPS using NGINX for a diner app.
In this tutorial, you will learn how to enforce HTTPS by redirecting all HTTP requests (port 80) to HTTPS (port 443) using NGINX. We’ll demonstrate this on a simple diner app currently served over HTTP.
Before you begin, ensure NGINX is installed and your TLS certificates (.pem and .key) are available in /etc/ssl/certs/.
root@ubuntu-host# ls -l /etc/nginx/sites-enabledtotal 4lrwxrwxrwx 1 root root 32 Feb 7 00:51 diner -> /etc/nginx/sites-available/diner
Open /etc/nginx/sites-available/diner—it currently listens only on HTTP:
Copy
Ask AI
server { listen 80; server_name diner.com; root /var/www/diner; index index.html index.htm index.nginx-debian.html; location / { # First attempt to serve request as file, # then as directory, then return a 404. try_files $uri $uri/ =404; }}
Create (or edit) /etc/nginx/sites-available/diner-https with two server blocks:
Copy
Ask AI
server { listen 80; server_name diner.com; # Redirect all HTTP requests to HTTPS return 301 https://$host$request_uri;}server { listen 443 ssl; server_name diner.com; # SSL certificates (already present on the system) ssl_certificate /etc/ssl/certs/diner.com.pem; ssl_certificate_key /etc/ssl/certs/diner.com-key.pem; root /var/www/diner; index index.html index.htm index.nginx-debian.html; location / { # First attempt to serve request as file, # then as directory, then return a 404. try_files $uri $uri/ =404; }}
Server Block
Purpose
Port
HTTP → HTTPS
Permanent redirect (301) to the same URI over TLS
80
HTTPS with SSL
Serves encrypted content using provided certificates
root@ubuntu-host# nginx -tnginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: configuration file /etc/nginx/nginx.conf test is successfulroot@ubuntu-host# nginx -s reload
If NGINX fails to reload, check for syntax errors in all files under /etc/nginx/ and confirm your certificate paths are correct.
Verify the redirect and HTTPS response:
HTTP → HTTPS redirect:
Copy
Ask AI
root@ubuntu-host# curl -I http://localhostHTTP/1.1 301 Moved PermanentlyLocation: https://localhost/Server: nginx/1.18.0 (Ubuntu)