Linux Tips guides, explanations and reader checklists on whilenetworking.com

How to Install and Configure a Reverse Proxy with Nginx on Ubuntu

A reverse proxy acts as an intermediary server that sits between clients and backend servers. It hides the internal structure of your application, manages…

A reverse proxy acts as an intermediary server that sits between clients and backend servers. It hides the internal structure of your application, manages traffic distribution, handles SSL termination, and provides an additional layer of security against direct attacks. For users running Ubuntu, Nginx is the industry-standard choice for setting up a lightweight, high-performance reverse proxy. This guide walks you through installing Nginx, configuring it to forward requests to a backend service, securing your connection with HTTPS, and verifying the setup in a real-world scenario.

Prerequisites and Security Considerations

Before beginning, ensure your Ubuntu system is updated to the latest version available in your repository. Running outdated software can introduce vulnerabilities that a reverse proxy is meant to mitigate. Execute the following commands to update your package lists and upgrade installed packages:

sudo apt update && sudo apt upgrade -y

You will need sudo privileges to install new packages or modify configuration files. If you are connecting clients from different networks or over the public internet, configuring SSL/TLS is mandatory. Nginx does not handle SSL termination out of the box; you must obtain certificates (via Let’s Encrypt) and configure the ssl_certificate paths correctly. Failure to do so will result in browser warnings or connection failures for your users.

Installing Nginx on Ubuntu

The installation process is straightforward using the APT package manager. First, add the official Nginx repository if you are using a version of Ubuntu that requires it (though standard repositories usually suffice). Then, install the package:

sudo apt install nginx -y

Once installed, verify that Nginx is running and listening on port 80 by checking its status. You should see output indicating an “active” state. If you attempt to open your server’s IP address in a browser at this stage, you will likely see the default nginx.com welcome page located at /etc/nginx/sites-enabled/default. This file is often removed or disabled during installation on newer Ubuntu versions, leaving only the main configuration file active.

Understanding the Configuration Structure

Nginx configuration files are stored in /etc/nginx/. The primary file is nginx.conf, which defines global settings like worker processes and error logs. Site-specific configurations are typically located in /etc/nginx/sites-available/ and symlinked to /etc/nginx/sites-enabled/. When configuring a reverse proxy, you will be editing a site configuration file (e.g., proxy.example.com).

The core logic of a reverse proxy involves defining an upstream block. This block tells Nginx where the backend server resides. You can define multiple upstream servers for load balancing or failover purposes. For example, if you have two application instances running on ports 8001 and 8002, you would list both in the upstream block.

Configuring the Reverse Proxy Rules

To configure Nginx to forward traffic, create a new configuration file in /etc/nginx/sites-available/ (e.g., myapp-proxy). Open the file with your text editor:

sudo nano /etc/nginx/sites-available/myapp-proxy

Define the upstream block first. Replace the IP address and port with your actual backend server details:

upstream backend_servers {
    server 192.168.1.50:8001;
    # server 192.168.1.50:8002; # Uncomment for load balancing
}

Next, define the server block that listens on port 80 (HTTP). Inside this block, use the location directive to match incoming requests and pass them to the upstream group using the proxy_pass directive.

server {
    listen 80;
    server_name myapp.example.com; # Replace with your domain or IP

    location / {
        proxy_pass http://backend_servers;

        # Essential headers for proper client interaction
        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;

        # Timeout settings to prevent hanging connections
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
}

The proxy_set_header directives are critical. Without them, the backend application might not know the original client’s IP address or the protocol used (HTTP vs HTTPS), leading to authentication failures or security issues.

Securing the Proxy with HTTPS and Let’s Encrypt

A reverse proxy without SSL is insecure for public use. To enable HTTPS, you need a certificate. The most common method on Ubuntu is using Certbot with Let’s Encrypt. First, install Certbot and the Nginx plugin:

sudo apt install certbot python3-certbot-nginx -y

Ensure your domain points to your Ubuntu server via DNS (A record). Then, run the automation script to obtain and configure the certificate:

sudo certbot --nginx -d myapp.example.com

Certbot will guide you through email verification. It will then automatically modify your Nginx configuration to add an if statement redirecting HTTP traffic to HTTPS and inserting the SSL certificate paths. Review the generated configuration in /etc/nginx/sites-available/myapp-proxy to ensure no custom settings were overwritten incorrectly, as Certbot sometimes appends blocks that conflict with manual edits. If conflicts arise, you may need to manually merge your custom location blocks back into the file or re-run Certbot with specific flags to preserve existing content.

Testing and Verifying the Setup

Before applying changes live, always test the Nginx configuration for syntax errors. A typo in quotes or brackets can cause Nginx to fail on startup. Run the following command:

sudo nginx -t

If the output says “syntax is ok” and “test is successful,” proceed to reload Nginx to apply the new configuration without dropping existing connections:

sudo systemctl reload nginx

To verify the reverse proxy is working, open a browser and navigate to your domain. You should see content served by your backend application, not the Nginx default page or an error screen. Use curl from the command line to inspect headers if you are debugging:

curl -I https://myapp.example.com

Check that the response comes from your backend and that the Server header indicates Nginx is handling the request.

Common Mistakes and Troubleshooting

One frequent mistake is forgetting to remove or disable the default site configuration (/etc/nginx/sites-enabled/default). If left active, it can conflict with your new reverse proxy rules, causing 403 Forbidden errors or serving the wrong content. Always check /etc/nginx/sites-enabled/ and ensure only your specific proxy configuration file exists there.

Another common issue is firewall restrictions. Even if Nginx is configured correctly, Ubuntu’s ufw (Uncomplicated Firewall) or cloud provider security groups might block port 80 and 443. Ensure these ports are open:

sudo ufw allow 'Nginx Full'

If you encounter 502 Bad Gateway errors, verify that the backend server is actually running and reachable from the Nginx server. Check the Nginx error log (/var/log/nginx/error.log) for specific connection refused or timeout messages. Misconfigured time synchronization between the proxy and backend servers can also cause SSL handshake failures; ensure both systems have synchronized clocks using chrony or ntp.

Conclusion

Setting up a reverse proxy with Nginx on Ubuntu is a fundamental step for securing and managing web traffic. By following these steps, you establish a robust entry point that handles SSL termination, hides your backend infrastructure, and ensures consistent client interactions. Remember to always test configurations before reloading and to keep your system updated. Terms, availability, and specific security requirements may vary based on your jurisdiction and local laws; always consult official Nginx documentation for the latest best practices.