How to Configure NGINX as a Reverse Proxy: A Step-by-Step Guide
Setting up NGINX as a reverse proxy is a powerful way to improve your web application’s performance, security, and scalability. Instead of exposing your backend servers directly, NGINX sits in front, forwarding client requests to the appropriate backend. This tutorial walks you through the configuration process with simple, actionable steps.
Before you begin, ensure NGINX is installed on your server (e.g., Ubuntu, CentOS) and you have sudo access. The basic principle remains the same across distributions.
1. Basic Reverse Proxy Configuration
Open your NGINX configuration file (usually /etc/nginx/sites-available/example.com or /etc/nginx/nginx.conf). Inside the server block, add a location directive:
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
Explanation: proxy_pass directs traffic to your backend (here, a Node.js app on port 3000). The proxy_set_header lines preserve the original client information.
2. Handling WebSocket Connections
If your backend uses WebSockets (e.g., live chat, real-time updates), add these lines inside the same location block:
proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade";
This allows NGINX to properly upgrade the connection to WebSocket protocol.
3. Optimizing Timeouts and Buffering
To avoid client timeouts or slow uploads, adjust these settings inside the location block:
proxy_read_timeout 300s; proxy_send_timeout 300s; proxy_buffering off;
proxy_buffering off is useful for streaming applications or real-time APIs where immediate response is critical.
4. Testing and Reloading
Always test your configuration for syntax errors:
sudo nginx -t
If the test passes, reload NGINX to apply changes:
sudo systemctl reload nginx
Verify by accessing your domain – the backend content should now be served through NGINX.
Conclusion
Configuring NGINX as a reverse proxy is straightforward once you understand the core directives. Start with the basic proxy_pass, then add headers, WebSocket support, and timeouts as needed. This setup centralizes traffic, simplifies SSL termination, and boosts your application’s reliability.