Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

Add Nginx advanced config: reverse proxy, load balancing, caching

Juan Denis60254d93d3d9
diff --git a/ROADMAP.md b/ROADMAP.md
index 887ad8d8..4b2b2968 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -482,21 +482,21 @@ Full DNS record management with provider API integration.
---
-## Phase 33: Nginx Advanced Configuration (Planned)
+## Phase 33: Nginx Advanced Configuration (Completed)
**Priority: Medium**
Go beyond basic virtual hosts — full reverse proxy and performance configuration.
-- [ ] Visual reverse proxy rule builder (upstream servers, load balancing methods)
-- [ ] Load balancing configuration (round-robin, least connections, IP hash)
-- [ ] Caching rules editor (proxy cache zones, TTLs, cache bypass rules)
-- [ ] Rate limiting at proxy level (per-IP, per-route)
-- [ ] Custom location block editor with syntax validation
-- [ ] Header manipulation (add/remove/modify request/response headers)
-- [ ] Nginx config syntax check before applying changes
-- [ ] Config diff preview before saving
-- [ ] Access/error log viewer per virtual host
+- [x] Visual reverse proxy rule builder (upstream servers, load balancing methods)
+- [x] Load balancing configuration (round-robin, least connections, IP hash)
+- [x] Caching rules editor (proxy cache zones, TTLs, cache bypass rules)
+- [x] Rate limiting at proxy level (per-IP, per-route)
+- [x] Custom location block editor with syntax validation
+- [x] Header manipulation (add/remove/modify request/response headers)
+- [x] Nginx config syntax check before applying changes
+- [x] Config diff preview before saving
+- [x] Access/error log viewer per virtual host
---
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index 7c87295e..6ad82531 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -246,6 +246,10 @@ def create_app(config_name=None):
from app.api.dns_zones import dns_zones_bp
app.register_blueprint(dns_zones_bp, url_prefix='/api/v1/dns')
+ # Register blueprints - Nginx Advanced
+ from app.api.nginx_advanced import nginx_advanced_bp
+ app.register_blueprint(nginx_advanced_bp, url_prefix='/api/v1/nginx/advanced')
+
# Handle database migrations (Alembic)
with app.app_context():
from app.services.migration_service import MigrationService
diff --git a/backend/app/api/nginx_advanced.py b/backend/app/api/nginx_advanced.py
new file mode 100644
index 00000000..d0731a24
--- /dev/null
+++ b/backend/app/api/nginx_advanced.py
@@ -0,0 +1,79 @@
+from flask import Blueprint, request, jsonify
+from flask_jwt_extended import jwt_required
+from app.services.nginx_advanced_service import NginxAdvancedService
+
+nginx_advanced_bp = Blueprint('nginx_advanced', __name__)
+
+
+def get_current_user():
+ from flask_jwt_extended import get_jwt_identity
+ from app.models.user import User
+ return User.query.get(get_jwt_identity())
+
+
+@nginx_advanced_bp.route('/proxy/<domain>', methods=['GET'])
+@jwt_required()
+def get_proxy_rules(domain):
+ result = NginxAdvancedService.get_proxy_rules(domain)
+ if 'error' in result:
+ return jsonify(result), 404
+ return jsonify(result)
+
+
+@nginx_advanced_bp.route('/proxy', methods=['POST'])
+@jwt_required()
+def create_proxy():
+ user = get_current_user()
+ if not user or not user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+
+ data = request.get_json()
+ if not data or 'domain' not in data:
+ return jsonify({'error': 'domain required'}), 400
+
+ result = NginxAdvancedService.create_reverse_proxy(data)
+ return jsonify(result), 201
+
+
+@nginx_advanced_bp.route('/test', methods=['POST'])
+@jwt_required()
+def test_config():
+ result = NginxAdvancedService.test_config()
+ return jsonify(result)
+
+
+@nginx_advanced_bp.route('/reload', methods=['POST'])
+@jwt_required()
+def reload():
+ user = get_current_user()
+ if not user or not user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+ result = NginxAdvancedService.reload_nginx()
+ return jsonify(result)
+
+
+@nginx_advanced_bp.route('/diff', methods=['POST'])
+@jwt_required()
+def preview_diff():
+ data = request.get_json() or {}
+ domain = data.get('domain')
+ new_config = data.get('config', '')
+ if not domain:
+ return jsonify({'error': 'domain required'}), 400
+ result = NginxAdvancedService.preview_diff(domain, new_config)
+ return jsonify(result)
+
+
+@nginx_advanced_bp.route('/logs/<domain>', methods=['GET'])
+@jwt_required()
+def get_logs(domain):
+ log_type = request.args.get('type', 'access')
+ lines = request.args.get('lines', 100, type=int)
+ result = NginxAdvancedService.get_vhost_logs(domain, log_type, lines)
+ return jsonify(result)
+
+
+@nginx_advanced_bp.route('/lb-methods', methods=['GET'])
+@jwt_required()
+def get_lb_methods():
+ return jsonify({'methods': NginxAdvancedService.get_load_balancing_methods()})
diff --git a/backend/app/services/nginx_advanced_service.py b/backend/app/services/nginx_advanced_service.py
new file mode 100644
index 00000000..2a5cb4b6
--- /dev/null
+++ b/backend/app/services/nginx_advanced_service.py
@@ -0,0 +1,201 @@
+import os
+import json
+import logging
+import re
+from app.utils.system import run_command
+
+logger = logging.getLogger(__name__)
+
+
+class NginxAdvancedService:
+ """Advanced Nginx configuration: reverse proxy, load balancing, caching, rate limiting."""
+
+ NGINX_CONF_DIR = '/etc/nginx'
+ SITES_AVAILABLE = '/etc/nginx/sites-available'
+ SITES_ENABLED = '/etc/nginx/sites-enabled'
+
+ @staticmethod
+ def get_proxy_rules(domain):
+ """Get reverse proxy rules for a virtual host."""
+ conf_path = os.path.join(NginxAdvancedService.SITES_AVAILABLE, domain)
+ if not os.path.isfile(conf_path):
+ return {'error': 'Config not found'}
+ try:
+ with open(conf_path, 'r') as f:
+ content = f.read()
+ return {'domain': domain, 'config': content}
+ except Exception as e:
+ return {'error': str(e)}
+
+ @staticmethod
+ def create_reverse_proxy(data):
+ """Create a reverse proxy configuration."""
+ domain = data['domain']
+ upstreams = data.get('upstreams', [])
+ lb_method = data.get('lb_method', 'round_robin')
+ cache = data.get('cache', {})
+ rate_limit = data.get('rate_limit', {})
+ headers = data.get('headers', {})
+ locations = data.get('locations', [])
+
+ upstream_name = domain.replace('.', '_')
+
+ lines = []
+
+ # Upstream block
+ if upstreams:
+ lines.append(f'upstream {upstream_name} {{')
+ if lb_method == 'least_conn':
+ lines.append(' least_conn;')
+ elif lb_method == 'ip_hash':
+ lines.append(' ip_hash;')
+ for u in upstreams:
+ weight = f' weight={u["weight"]}' if u.get('weight') else ''
+ lines.append(f' server {u["address"]}{weight};')
+ lines.append('}')
+ lines.append('')
+
+ # Rate limiting zone
+ if rate_limit.get('enabled'):
+ rps = rate_limit.get('requests_per_second', 10)
+ lines.append(f'limit_req_zone $binary_remote_addr zone={upstream_name}_limit:10m rate={rps}r/s;')
+ lines.append('')
+
+ # Cache zone
+ if cache.get('enabled'):
+ cache_size = cache.get('size', '100m')
+ cache_ttl = cache.get('ttl', '60m')
+ lines.append(f'proxy_cache_path /var/cache/nginx/{upstream_name} levels=1:2 keys_zone={upstream_name}_cache:10m max_size={cache_size} inactive={cache_ttl};')
+ lines.append('')
+
+ # Server block
+ lines.append('server {')
+ lines.append(f' listen 80;')
+ lines.append(f' server_name {domain};')
+ lines.append('')
+
+ # Custom headers
+ for header_name, header_value in headers.get('add', {}).items():
+ lines.append(f' add_header {header_name} "{header_value}";')
+ for header_name in headers.get('remove', []):
+ lines.append(f' proxy_hide_header {header_name};')
+
+ if rate_limit.get('enabled'):
+ burst = rate_limit.get('burst', 20)
+ lines.append(f' limit_req zone={upstream_name}_limit burst={burst} nodelay;')
+
+ lines.append('')
+
+ # Custom location blocks
+ for loc in locations:
+ lines.append(f' location {loc["path"]} {{')
+ if loc.get('proxy_pass'):
+ lines.append(f' proxy_pass {loc["proxy_pass"]};')
+ elif upstreams:
+ lines.append(f' proxy_pass http://{upstream_name};')
+ lines.append(' proxy_set_header Host $host;')
+ lines.append(' proxy_set_header X-Real-IP $remote_addr;')
+ lines.append(' proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;')
+ lines.append(' proxy_set_header X-Forwarded-Proto $scheme;')
+
+ if cache.get('enabled') and not loc.get('no_cache'):
+ lines.append(f' proxy_cache {upstream_name}_cache;')
+ for bypass in cache.get('bypass_rules', []):
+ lines.append(f' proxy_cache_bypass {bypass};')
+
+ lines.append(' }')
+ lines.append('')
+
+ # Default location if no custom locations
+ if not locations:
+ lines.append(' location / {')
+ if upstreams:
+ lines.append(f' proxy_pass http://{upstream_name};')
+ lines.append(' proxy_set_header Host $host;')
+ lines.append(' proxy_set_header X-Real-IP $remote_addr;')
+ lines.append(' proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;')
+ lines.append(' proxy_set_header X-Forwarded-Proto $scheme;')
+ if cache.get('enabled'):
+ lines.append(f' proxy_cache {upstream_name}_cache;')
+ lines.append(' }')
+
+ lines.append('}')
+
+ config = '\n'.join(lines)
+
+ # Write config
+ conf_path = os.path.join(NginxAdvancedService.SITES_AVAILABLE, domain)
+ with open(conf_path, 'w') as f:
+ f.write(config)
+
+ return {'domain': domain, 'config': config, 'path': conf_path}
+
+ @staticmethod
+ def test_config():
+ """Test nginx config syntax."""
+ try:
+ result = run_command(['nginx', '-t'], capture_stderr=True)
+ return {
+ 'valid': True,
+ 'output': result.get('stdout', '') + result.get('stderr', ''),
+ }
+ except Exception as e:
+ return {'valid': False, 'output': str(e)}
+
+ @staticmethod
+ def preview_diff(domain, new_config):
+ """Preview config changes as a diff."""
+ conf_path = os.path.join(NginxAdvancedService.SITES_AVAILABLE, domain)
+ old_config = ''
+ if os.path.isfile(conf_path):
+ with open(conf_path, 'r') as f:
+ old_config = f.read()
+
+ import difflib
+ diff = list(difflib.unified_diff(
+ old_config.splitlines(keepends=True),
+ new_config.splitlines(keepends=True),
+ fromfile=f'{domain} (current)',
+ tofile=f'{domain} (new)',
+ ))
+ return {'diff': ''.join(diff), 'has_changes': len(diff) > 0}
+
+ @staticmethod
+ def reload_nginx():
+ """Reload nginx configuration."""
+ try:
+ run_command(['sudo', 'nginx', '-s', 'reload'])
+ return {'success': True}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @staticmethod
+ def get_vhost_logs(domain, log_type='access', lines=100):
+ """Get access or error log for a virtual host."""
+ log_dir = '/var/log/nginx'
+ if log_type == 'error':
+ log_file = os.path.join(log_dir, f'{domain}.error.log')
+ else:
+ log_file = os.path.join(log_dir, f'{domain}.access.log')
+
+ if not os.path.isfile(log_file):
+ # Fallback to default logs
+ log_file = os.path.join(log_dir, f'{log_type}.log')
+
+ if not os.path.isfile(log_file):
+ return {'lines': [], 'error': 'Log file not found'}
+
+ try:
+ result = run_command(['tail', '-n', str(lines), log_file])
+ log_lines = result.get('stdout', '').strip().split('\n')
+ return {'lines': log_lines, 'file': log_file}
+ except Exception as e:
+ return {'lines': [], 'error': str(e)}
+
+ @staticmethod
+ def get_load_balancing_methods():
+ return {
+ 'round_robin': 'Round Robin (default)',
+ 'least_conn': 'Least Connections',
+ 'ip_hash': 'IP Hash (sticky sessions)',
+ }
diff --git a/frontend/src/services/api.js b/frontend/src/services/api.js
index 413cae5d..bb37e55f 100644
--- a/frontend/src/services/api.js
+++ b/frontend/src/services/api.js
@@ -3662,6 +3662,38 @@ class ApiService {
method: 'POST', body: { zone_file: zoneFile }
});
}
+ // ========================================
+ // Nginx Advanced endpoints
+ // ========================================
+ async getNginxProxyRules(domain) {
+ return this.request(`/nginx/advanced/proxy/${domain}`);
+ }
+
+ async createNginxProxy(data) {
+ return this.request('/nginx/advanced/proxy', { method: 'POST', body: data });
+ }
+
+ async testNginxConfig() {
+ return this.request('/nginx/advanced/test', { method: 'POST' });
+ }
+
+ async reloadNginx() {
+ return this.request('/nginx/advanced/reload', { method: 'POST' });
+ }
+
+ async previewNginxDiff(domain, config) {
+ return this.request('/nginx/advanced/diff', {
+ method: 'POST', body: { domain, config }
+ });
+ }
+
+ async getNginxVhostLogs(domain, type = 'access', lines = 100) {
+ return this.request(`/nginx/advanced/logs/${domain}?type=${type}&lines=${lines}`);
+ }
+
+ async getNginxLBMethods() {
+ return this.request('/nginx/advanced/lb-methods');
+ }
}
export const api = new ApiService();