1. Install and Configure Nginx:
-
Install Nginx:If you haven’t already, install Nginx on your server. On Ubuntu/Debian, you can use
sudo apt update && sudo apt install nginx
. -
Enable Firewall (Optional but Recommended):If you’re using a firewall (like
ufw
), allow traffic on ports 80 and 443:sudo ufw allow 'Nginx Full'
. -
Configure Nginx:Edit the Nginx configuration file, typically
/etc/nginx/nginx.conf
or/etc/nginx/sites-available/default
. You’ll need to create aserver
block for HTTPS.
2. Configure the HTTPS Server Block:
Code
server {
listen 443 ssl; server_name your_domain.com; # Replace with your domain ssl_certificate /path/to/your/certificate.pem; # Replace with your SSL certificate path ssl_certificate_key /path/to/your/certificate.key; # Replace with your SSL key path location / { proxy_pass https://backend_server_ip:backend_port; # Replace with the backend server's IP and port proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } }
listen 443 ssl;
: Tells Nginx to listen for HTTPS traffic on port 443.server_name your_domain.com;
: Replace with your domain name.ssl_certificate
andssl_certificate_key
: Specify the paths to your SSL certificate and private key files.proxy_pass https://backend_server_ip:backend_port;
: This is the core of the reverse proxy. It tells Nginx to forward requests to the backend server (e.g.,https://192.168.1.100:8443
). Use the correct IP address and port for your backend server.proxy_set_header
directives: These headers help the backend server understand the original client’s information and can be customized as needed.
3. Handling HTTP (Optional, but Recommended):
To automatically redirect HTTP traffic to HTTPS, add another server block:
Code
how to reverse proxy https in nginx using another sever
server {
listen 80; server_name your_domain.com; return 301 https://$host$request_uri; # Redirect all HTTP traffic to HTTPS }
This block listens on port 80 (HTTP), and any request to this port will be redirected to the HTTPS version of the same URL.
4. Test and Deploy:
- Test the configuration:
sudo nginx -t
. Correct any errors reported by the test. - Restart Nginx:
sudo systemctl restart nginx
orsudo service nginx restart
. - Verify: Access your domain (e.g.,
https://your_domain.com
) in your browser. You should see the content of your backend server, and the connection should be secure (HTTPS).