Introduction
A reverse proxy sits in front of your backend web servers (like Node.js, Python/Gunicorn, or Tomcat) and forwards client requests to those servers. Nginx is the industry standard for this task. Using Nginx as a reverse proxy improves security, simplifies SSL/TLS termination, and allows for efficient load balancing. This guide explains how to configure a basic Nginx reverse proxy on a Linux server.
Prerequisites
You require a Linux server (e.g., Ubuntu, Debian, or AlmaLinux) with root or sudo access. You also need an application running on an internal port (e.g., a Node.js app running on `http://127.0.0.1:3000`).
Step 1: Install Nginx
First, update your package manager and install Nginx. On Debian/Ubuntu:
sudo apt update && sudo apt install nginx
On RHEL/CentOS/AlmaLinux:
sudo dnf install nginx
Enable Nginx to start on boot and start the service:
sudo systemctl enable --now nginx
Step 2: Create a Server Block Configuration
Instead of editing the main `nginx.conf` file, you should create a dedicated server block (virtual host) configuration for your application. Create a new file in the `sites-available` directory (Ubuntu/Debian) or `conf.d` directory (RHEL).
sudo nano /etc/nginx/sites-available/myapp.example.com
Add the following configuration. Replace `myapp.example.com` with your actual domain name and `3000` with your application’s port:
server {
listen 80;
server_name myapp.example.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
This configuration instructs Nginx to listen on port 80 for requests to `myapp.example.com` and forward them to localhost port 3000. The `proxy_set_header` directives ensure that the backend application receives the correct client IP addresses and host headers, rather than assuming all traffic originates from Nginx itself.
Step 3: Enable the Configuration
If you are using Ubuntu/Debian, you must create a symbolic link from `sites-available` to `sites-enabled` to activate the configuration.
sudo ln -s /etc/nginx/sites-available/myapp.example.com /etc/nginx/sites-enabled/
Step 4: Test and Reload Nginx
Before reloading the service, it is critical to verify the Nginx configuration syntax to prevent downtime.
sudo nginx -t
If the output indicates that the syntax is OK and the test is successful, reload Nginx to apply the changes:
sudo systemctl reload nginx
Your application is now accessible via the standard HTTP port 80 through the Nginx reverse proxy. For production environments, it is highly recommended to secure this setup further by installing a Let’s Encrypt SSL certificate using Certbot.