Managing large nginx.conf files becomes increasingly difficult as your web applications grow. When a single server block contains dozens of location directives, making changes becomes risky and time-consuming. The solution? Modular configuration through file splitting.
Follow these principles when breaking up your config:
- Maintain a single root definition in the main file
- Group related locations together (by functionality or URL prefix)
- Use descriptive filenames (admin_locations.conf, api_endpoints.conf)
- Keep the include directive clean and organized
Original server block (nginx.conf):
server {
listen 80 default_server;
root /var/www/;
include /etc/nginx/locations/*.conf;
}
Sample location config file (/etc/nginx/locations/api.conf):
location /api/v1 {
proxy_pass http://backend_api;
proxy_set_header Host $host;
}
location /api/v2 {
proxy_pass http://new_backend;
proxy_http_version 1.1;
}
For complex setups, consider:
# Main nginx.conf
http {
include /etc/nginx/conf.d/*.conf;
}
# conf.d/default_server.conf
server {
include locations/general.conf;
include locations/admin.conf;
include locations/legacy.conf;
}
Always test your configuration:
sudo nginx -t
sudo systemctl reload nginx
This approach gives you the flexibility to disable entire feature sets by simply commenting out include directives, while maintaining clean separation of concerns.
When managing complex web applications, monolithic nginx configuration files become unwieldy. The solution lies in modularization - splitting configurations into logical components while maintaining proper inheritance and avoiding path resolution issues.
Follow these key rules when breaking up configurations:
# 1. Maintain single root declaration
# 2. Group related locations logically
# 3. Preserve proper include directive order
# 4. Use absolute paths for includes
Original server block (nginx.conf):
server {
listen 80 default_server;
root /var/www/;
include /etc/nginx/conf.d/locations/*.conf;
}
Sample location file (/etc/nginx/conf.d/locations/api.conf):
location /api/v1 {
proxy_pass http://backend;
proxy_set_header Host $host;
}
location /api/v2 {
proxy_pass http://new-backend;
proxy_http_version 1.1;
}
For large-scale deployments:
# /etc/nginx/conf.d/
# ├── server-core.conf
# ├── locations/
# │ ├── static.conf
# │ ├── api.conf
# │ └── admin.conf
# └── upstreams/
# ├── backend.conf
# └── cache.conf
- Path conflicts: Always use absolute paths in includes
- Variable scope: Define global variables in main config
- Order dependency: Prefix files numerically (00-core.conf, 10-locations.conf)
While includes add minimal overhead, consider:
# Merge includes during deployment
cat /etc/nginx/conf.d/locations/*.conf > /etc/nginx/locations_combined.conf
How to Modularize Nginx Configuration: Splitting Large server Blocks into Maintainable Location-Specific Files
2 views