Path-Based Routing in Nginx
Introduction
Path-based routing allows directing requests to different backends based on the URL path. This is commonly used in microservices, reverse proxy setups, and load balancing.
Prerequisites
- Installed Nginx
- Basic understanding of Nginx configuration
- Access to Nginx configuration files (e.g.,
/etc/nginx/nginx.conf
or/etc/nginx/sites-available/default
)
Configuration
Below is an example Nginx configuration for path-based routing:
server {
listen 80;
server_name example.com;
location /app1/ {
proxy_pass http://backend_app1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
location /app2/ {
proxy_pass http://backend_app2;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
location /php-app/ {
root /var/www/php-app;
index index.php;
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/run/php/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
location /react-app/ {
root /var/www/react-app;
index index.html;
try_files $uri /index.html;
}
location /java-app/ {
proxy_pass http://backend_java_app;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
location /nodejs-app/ {
proxy_pass http://backend_nodejs_app;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
Explanation:
- Requests to
example.com/app1/
will be forwarded tohttp://backend_app1
. - Requests to
example.com/app2/
will be forwarded tohttp://backend_app2
. - Requests to
example.com/php-app/
will serve a PHP application using FastCGI and PHP-FPM. - Requests to
example.com/react-app/
will serve a React application, ensuring the front-end routing works correctly. - Requests to
example.com/java-app/
will be forwarded to a Java-based backend service. - Requests to
example.com/nodejs-app/
will be forwarded to a Node.js backend service. proxy_set_header
ensures proper headers are forwarded to the backend.
Defining Backend Services
Define backend servers in the http
block:
http {
upstream backend_app1 {
server 192.168.1.10:8080;
}
upstream backend_app2 {
server 192.168.1.11:8080;
}
upstream backend_java_app {
server 192.168.1.12:8080;
}
upstream backend_nodejs_app {
server 192.168.1.13:3000;
}
}
Testing the Configuration
After making changes, test the configuration:
nginx -t
If there are no errors, reload Nginx:
systemctl reload nginx
Conclusion
Path-based routing in Nginx enables efficient request forwarding based on URL paths. This method is essential for microservices, API gateways, and reverse proxy setups.