How To Configure Nginx Reverse Proxy on Ubuntu 24.04 LTS
Nginx, a powerful and versatile web server, has become an indispensable tool for modern web applications. One of its most valuable features is its ability to function as a reverse proxy. This capability allows Nginx to act as an intermediary between clients and backend servers, offering benefits such as load balancing, enhanced security, and improved performance through caching.
In this comprehensive guide, we’ll walk you through the process of configuring Nginx as a reverse proxy on Ubuntu 24.04. Whether you’re a system administrator looking to optimize your server setup or a developer aiming to enhance your application’s architecture, this tutorial will provide you with the knowledge and steps needed to leverage Nginx’s reverse proxy capabilities effectively.
Prerequisites
Before we dive into the configuration process, ensure you have the following:
- A server running Ubuntu 24.04 LTS
- Root or sudo privileges on your server
- Basic familiarity with Linux command-line operations
- A domain name pointing to your server’s IP address (recommended but optional)
- An SSH client for remote server access
- A text editor such as Nano or Vim (pre-installed on most Ubuntu systems)
With these prerequisites in place, let’s begin the configuration process.
Step 1: Update System and Install Nginx
Keeping your system up-to-date is crucial for security and performance. Let’s start by updating the package lists and upgrading installed packages:
sudo apt update
sudo apt upgrade -y
Once your system is up-to-date, install Nginx using the following command:
sudo apt install nginx -y
After the installation completes, verify that Nginx is running:
systemctl status nginx
You should see output indicating that Nginx is active and running. By default, Nginx listens on port 80 for HTTP traffic.
Step 2: Configure Firewall Rules
Proper firewall configuration is essential for securing your server while allowing necessary traffic. Ubuntu comes with UFW (Uncomplicated Firewall) pre-installed. Let’s configure it to allow HTTP and HTTPS traffic:
sudo ufw allow 'Nginx Full'
This command opens both ports 80 (HTTP) and 443 (HTTPS) for Nginx. Verify the firewall status with:
sudo ufw status
Ensure that the output shows that Nginx Full is allowed.
Step 3: Create a Test Backend Application (Optional)
To effectively demonstrate the reverse proxy setup, it’s helpful to have a backend application. We’ll create a simple Python Flask application for this purpose.
First, install the necessary Python packages:
sudo apt install python3-pip
pip3 install gunicorn flask
Now, create a new file named app.py
with the following content:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello from the backend server!"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
This simple Flask application will serve as our backend. To run it using Gunicorn, execute:
gunicorn --bind localhost:5000 app:app
Your test application is now running on localhost:5000
.
Step 4: Configure Nginx as a Reverse Proxy
With our backend application running, let’s configure Nginx to act as a reverse proxy.
4.1 Create a New Server Block
Navigate to the Nginx configuration directory:
cd /etc/nginx/sites-available/
Create a new configuration file for our reverse proxy setup:
sudo nano reverse-proxy.conf
4.2 Add Reverse Proxy Configuration
In the newly created file, add the following configuration:
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://localhost:5000;
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;
}
}
Let’s break down this configuration:
listen 80;
tells Nginx to listen on port 80 for incoming HTTP requests.server_name yourdomain.com;
specifies the domain name for this server block. Replace with your actual domain.location / { ... }
defines how Nginx should handle requests for the root URL and its subdirectories.proxy_pass http://localhost:5000;
forwards requests to our backend application running on localhost:5000.- The
proxy_set_header
directives pass important information about the original request to the backend server.
4.3 Enable the Configuration
To enable the new configuration, create a symbolic link in the sites-enabled
directory:
sudo ln -s /etc/nginx/sites-available/reverse-proxy.conf /etc/nginx/sites-enabled/
Test the Nginx configuration for any syntax errors:
sudo nginx -t
If the test is successful, reload Nginx to apply the changes:
sudo systemctl reload nginx
Step 5: Secure Nginx with SSL/TLS
Securing your reverse proxy with SSL/TLS is crucial for protecting data in transit. We’ll use Let’s Encrypt to obtain a free SSL certificate.
5.1 Install Certbot
Certbot is a tool that simplifies the process of obtaining and installing SSL certificates. Install Certbot and its Nginx plugin:
sudo apt install certbot python3-certbot-nginx -y
5.2 Obtain an SSL Certificate
Run Certbot to obtain and automatically configure SSL for your domain:
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
Follow the prompts to complete the certificate installation. Certbot will modify your Nginx configuration to use the new certificate.
To ensure that your certificate will renew automatically, test the renewal process:
sudo certbot renew --dry-run
5.3 Update Configuration for HTTPS
After obtaining the SSL certificate, your reverse-proxy.conf
file should have been automatically updated. However, it’s good practice to review and ensure it includes the necessary SSL configurations:
server {
listen [::]:80;
listen [::]:443 ssl http2;
server_name yourdomain.com www.yourdomain.com;
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
location / {
proxy_pass http://localhost:5000;
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;
}
# Additional SSL settings can be added here
}
This configuration ensures that your site is accessible via both HTTP and HTTPS, with HTTPS being the preferred method.
Step 6: Test and Troubleshoot Configuration
6.1 Verify Reverse Proxy Setup
To test your reverse proxy configuration, open a web browser and navigate to your domain. You should see the “Hello from the backend server!” message from your Flask application.
6.2 Common Issues and Fixes
If you encounter issues, here are some common problems and their solutions:
- Nginx Fails to Start: Check for syntax errors in your configuration files using
nginx -t
. Look for typos or missing semicolons. - 502 Bad Gateway Error: This often occurs when Nginx can’t connect to the backend server. Ensure your Flask application is running and that the
proxy_pass
directive in your Nginx configuration points to the correct address and port. - SSL Certificate Issues: If you’re having trouble with SSL, verify that Certbot completed successfully and that the SSL certificate paths in your Nginx configuration are correct.
- Firewall Blocking Traffic: Double-check your UFW settings to ensure that HTTP and HTTPS traffic is allowed.
Advanced Configurations
Once you have a basic reverse proxy setup working, consider exploring these advanced configurations to further enhance your server’s capabilities:
Load Balancing
Nginx can distribute traffic across multiple backend servers, improving performance and reliability. Here’s a simple example of load balancing configuration:
upstream backend {
server backend1.example.com;
server backend2.example.com;
server backend3.example.com;
}
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://backend;
}
}
Caching
Implement caching to reduce the load on your backend servers and improve response times:
http {
proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_cache my_cache;
proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;
proxy_cache_valid 200 60m;
proxy_cache_valid 404 10m;
proxy_pass http://backend;
}
}
}
WebSocket Support
If your application uses WebSockets, add the following to your location block:
location /websocket {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
Congratulations! You have successfully set up Nginx Reverse Proxy. Thanks for using this tutorial to Configure Nginx Reverse Proxy on Ubuntu 24.04 LTS system. For additional or useful information, we recommend you check the official Nginx website.