Skip to content

Reverse Proxy Setup

VetheonGames edited this page Oct 10, 2025 · 1 revision

Reverse Proxy Setup

Complete guide for setting up a reverse proxy with Nginx or Apache to make Source-License publicly accessible with SSL/HTTPS support.

πŸ“‹ Overview

A reverse proxy sits between your users and the Source-License application, providing several benefits:

  • SSL/HTTPS Termination: Secure connections with automatic certificate management
  • Load Balancing: Distribute traffic across multiple application instances
  • Caching: Improve performance by caching static assets
  • Security: Hide internal application details and add security headers
  • Custom Domains: Serve the application on your domain name

πŸ—οΈ Architecture

Internet β†’ [Reverse Proxy] β†’ [Source-License App]
   :80        :80/:443           :4567
   :443

The reverse proxy receives all incoming requests on ports 80 (HTTP) and 443 (HTTPS) and forwards them to the Source-License application running on port 4567.

🌐 Nginx Setup (Recommended)

Nginx is the recommended reverse proxy due to its performance, simplicity, and excellent SSL support.

Prerequisites

  • Source-License installed and running on port 4567
  • Domain name pointing to your server's IP address
  • Root access to install and configure Nginx

1. Install Nginx

Ubuntu/Debian:

sudo apt update
sudo apt install nginx

CentOS/RHEL:

sudo yum install epel-release
sudo yum install nginx

Enable and start Nginx:

sudo systemctl enable nginx
sudo systemctl start nginx

2. Basic Configuration

Create a new site configuration:

sudo nano /etc/nginx/sites-available/source-license

Basic HTTP Configuration:

Note: Feel free to remove any section from this marked as "optional". If you have any issues with this config, please join our discord and ask for help!

server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;
    
    # Redirect all HTTP traffic to HTTPS
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name yourdomain.com www.yourdomain.com;
    
    # SSL Configuration (certificates will be added by Certbot)
    ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
    
    # Security Headers
    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    
    # Proxy Settings
    location / {
        proxy_pass http://127.0.0.1:4567;
        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;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Port $server_port;
        
        # WebSocket support (optional)
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        
        # Timeouts
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
    
    # Static file handling (optional optimization)
    location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
        proxy_pass http://127.0.0.1:4567;
        proxy_cache_bypass $http_pragma;
        proxy_cache_revalidate on;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
    
    # Security: Block access to sensitive files
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }
    
    location ~ \.(env|rb|log|sql)$ {
        deny all;
        access_log off;
        log_not_found off;
    }
}

3. Enable the Site

# Enable the site
sudo ln -s /etc/nginx/sites-available/source-license /etc/nginx/sites-enabled/

# Remove default site (optional)
sudo rm /etc/nginx/sites-enabled/default

# Test configuration
sudo nginx -t

# Reload Nginx
sudo systemctl reload nginx

4. SSL Setup with Let's Encrypt

Install Certbot for automatic SSL certificates:

# Ubuntu/Debian
sudo apt install certbot python3-certbot-nginx

# CentOS/RHEL
sudo yum install certbot python3-certbot-nginx

Generate SSL Certificate:

sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com

Auto-renewal setup:

# Test renewal
sudo certbot renew --dry-run

# Certbot automatically adds a cron job, but you can verify:
sudo crontab -l | grep certbot

5. Advanced Nginx Configuration

Performance Optimization:

# Add to /etc/nginx/nginx.conf in http block

# Gzip compression
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_proxied expired no-cache no-store private must-revalidate auth;
gzip_types
    text/plain
    text/css
    text/xml
    text/javascript
    application/javascript
    application/xml+rss
    application/json;

# File upload limits (adjust as needed)
client_max_body_size 50M;

# Connection limits
limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;
limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=5r/s;

Rate Limiting in Site Config:

server {
    # ... existing configuration ...
    
    # Apply rate limiting
    limit_conn conn_limit_per_ip 10;
    limit_req zone=req_limit_per_ip burst=10 nodelay;
    
    # Admin panel extra protection
    location /admin {
        limit_req zone=req_limit_per_ip burst=3 nodelay;
        proxy_pass http://127.0.0.1:4567;
        # ... other proxy settings ...
    }
}

πŸͺΆ Apache Setup (Alternative)

Apache is a solid alternative to Nginx, especially if you're already familiar with it.

Note: We strongly recommend using Nginx for support reasons. Our team is not very familiar with Apache, and thus support may be sub-par if not community only.

1. Install Apache

Ubuntu/Debian:

sudo apt update
sudo apt install apache2
sudo a2enmod proxy proxy_http ssl rewrite headers

CentOS/RHEL:

sudo yum install httpd mod_ssl

2. Apache Configuration

Create a virtual host configuration:

sudo nano /etc/apache2/sites-available/source-license.conf

Apache Virtual Host:

<VirtualHost *:80>
    ServerName yourdomain.com
    ServerAlias www.yourdomain.com
    
    # Redirect all HTTP to HTTPS
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</VirtualHost>

<VirtualHost *:443>
    ServerName yourdomain.com
    ServerAlias www.yourdomain.com
    
    # SSL Configuration
    SSLEngine on
    SSLCertificateFile /etc/letsencrypt/live/yourdomain.com/cert.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/yourdomain.com/privkey.pem
    SSLCertificateChainFile /etc/letsencrypt/live/yourdomain.com/chain.pem
    
    # Security Headers
    Header always set X-Frame-Options DENY
    Header always set X-Content-Type-Options nosniff
    Header always set X-XSS-Protection "1; mode=block"
    Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
    
    # Proxy Configuration
    ProxyPreserveHost On
    ProxyRequests Off
    
    ProxyPass / http://127.0.0.1:4567/
    ProxyPassReverse / http://127.0.0.1:4567/
    
    # Set headers for the backend
    ProxyPassReverse / http://127.0.0.1:4567/
    ProxyPassReverseAdjustCookiePath / /
    
    # Handle WebSockets (if needed)
    RewriteEngine On
    RewriteCond %{HTTP:Upgrade} websocket [NC]
    RewriteCond %{HTTP:Connection} upgrade [NC]
    RewriteRule ^/?(.*) "ws://127.0.0.1:4567/$1" [P,L]
    
    # Security: Block sensitive files
    <LocationMatch "\.(env|rb|log|sql)$">
        Require all denied
    </LocationMatch>
    
    <LocationMatch "^/\.">
        Require all denied
    </LocationMatch>
    
    # Logging
    ErrorLog ${APACHE_LOG_DIR}/source-license_error.log
    CustomLog ${APACHE_LOG_DIR}/source-license_access.log combined
</VirtualHost>

3. Enable Apache Site

# Enable the site
sudo a2ensite source-license.conf

# Disable default site
sudo a2dissite 000-default.conf

# Test configuration
sudo apache2ctl configtest

# Restart Apache
sudo systemctl restart apache2

4. SSL Setup for Apache

# Install Certbot for Apache
sudo apt install certbot python3-certbot-apache  # Ubuntu/Debian
sudo yum install certbot python3-certbot-apache  # CentOS/RHEL

# Generate certificate
sudo certbot --apache -d yourdomain.com -d www.yourdomain.com

πŸ”§ Source-License Configuration

Update your Source-License .env file to work with the reverse proxy:

# Application settings
APP_HOST=127.0.0.1
APP_PORT=4567

# Security settings for reverse proxy
FORCE_SSL=true
ALLOWED_HOSTS=yourdomain.com,www.yourdomain.com

# If you're using a CDN or multiple proxies
TRUSTED_PROXIES=127.0.0.1,::1

# Session configuration
SESSION_SECURE=true
SESSION_SAME_SITE=strict

Restart Source-License after making these changes:

# If using systemd service
sudo systemctl restart source-license

# If running manually
pkill -f "ruby.*launch.rb"
ruby launch.rb

πŸ”’ Security Best Practices

1. Firewall Configuration

Only allow necessary ports:

# UFW (Ubuntu/Debian)
sudo ufw allow 22/tcp    # SSH
sudo ufw allow 80/tcp    # HTTP
sudo ufw allow 443/tcp   # HTTPS
sudo ufw deny 4567/tcp   # Block direct access to app
sudo ufw enable

# FirewallD (CentOS/RHEL)
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --permanent --remove-port=4567/tcp
sudo firewall-cmd --reload

2. Additional Security Headers

Add these to your reverse proxy configuration:

# Nginx
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:";
add_header Referrer-Policy "strict-origin-when-cross-origin";
add_header Permissions-Policy "geolocation=(), microphone=(), camera=()";
# Apache
Header always set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
Header always set Permissions-Policy "geolocation=(), microphone=(), camera=()"

3. Rate Limiting

Implement rate limiting to prevent abuse:

Nginx with nginx-limit-req:

# In http block
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;

# In server block
location /admin/login {
    limit_req zone=login burst=3 nodelay;
    # ... proxy settings ...
}

location /api/ {
    limit_req zone=api burst=10 nodelay;
    # ... proxy settings ...
}

Apache with mod_evasive:

# Install mod_evasive
sudo apt install libapache2-mod-evasive  # Ubuntu/Debian
sudo a2enmod evasive

# Configure in /etc/apache2/mods-available/evasive.conf
<IfModule mod_evasive24.c>
    DOSHashTableSize    2048
    DOSPageCount        3
    DOSPageInterval     1
    DOSSiteCount        50
    DOSSiteInterval     1
    DOSBlockingPeriod   600
</IfModule>

πŸ“Š Monitoring and Logging

1. Access Logs

Monitor your reverse proxy logs:

Nginx:

# Real-time monitoring
sudo tail -f /var/log/nginx/access.log

# Error monitoring
sudo tail -f /var/log/nginx/error.log

Apache:

# Access logs
sudo tail -f /var/log/apache2/source-license_access.log

# Error logs
sudo tail -f /var/log/apache2/source-license_error.log

2. Log Analysis

Useful log analysis commands:

# Top IP addresses
sudo awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -10

# Most requested pages
sudo awk '{print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -10

# Error analysis
sudo grep "ERROR\|WARN" /var/log/nginx/error.log | tail -20

3. Health Monitoring

Create a simple health check:

# Create health check script
sudo nano /usr/local/bin/source-license-health.sh
#!/bin/bash
# Health check for Source-License

URL="https://yourdomain.com/api/health"
EXPECTED="200"

HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "$URL")

if [ "$HTTP_CODE" -eq "$EXPECTED" ]; then
    echo "βœ… Source-License is healthy (HTTP $HTTP_CODE)"
    exit 0
else
    echo "❌ Source-License health check failed (HTTP $HTTP_CODE)"
    exit 1
fi
# Make executable
sudo chmod +x /usr/local/bin/source-license-health.sh

# Add to crontab for regular checks
(crontab -l ; echo "*/5 * * * * /usr/local/bin/source-license-health.sh >> /var/log/source-license-health.log 2>&1") | crontab -

πŸ› Troubleshooting

Common Issues

502 Bad Gateway Error:

nginx: 502 Bad Gateway
apache: Service Temporarily Unavailable

Solutions:

  • Check if Source-License is running: ps aux | grep ruby
  • Verify port 4567 is accessible: curl http://localhost:4567
  • Check firewall rules
  • Review application logs

SSL Certificate Issues:

SSL_ERROR_BAD_CERT_DOMAIN

Solutions:

  • Verify DNS is pointing to your server
  • Check certificate validity: sudo certbot certificates
  • Renew certificate: sudo certbot renew

Connection Timeout:

upstream timed out

Solutions:

  • Increase proxy timeout values
  • Check Source-License performance
  • Monitor system resources (CPU, RAM)

Permission Denied:

Permission denied while connecting to upstream

Solutions:

  • Check SELinux settings: sudo setsebool -P httpd_can_network_connect 1
  • Verify file permissions
  • Check if Source-License is binding to correct interface

Debug Commands

# Test reverse proxy configuration
curl -I http://localhost
curl -I https://yourdomain.com

# Check SSL certificate
openssl s_client -connect yourdomain.com:443 -servername yourdomain.com

# Test direct application access
curl -I http://localhost:4567

# Check process status
sudo systemctl status nginx  # or apache2
sudo systemctl status source-license

# Monitor real-time logs
sudo journalctl -f -u nginx  # or apache2

Performance Tuning

Nginx Worker Optimization:

# /etc/nginx/nginx.conf
worker_processes auto;
worker_connections 1024;
keepalive_timeout 65;

Apache Tuning:

# /etc/apache2/mods-available/mpm_prefork.conf
<IfModule mpm_prefork_module>
    StartServers 5
    MinSpareServers 5
    MaxSpareServers 10
    MaxRequestWorkers 150
    MaxConnectionsPerChild 0
</IfModule>

πŸ”„ Maintenance

1. Regular Updates

Keep your reverse proxy updated:

# Ubuntu/Debian
sudo apt update && sudo apt upgrade nginx  # or apache2

# CentOS/RHEL
sudo yum update nginx  # or httpd

2. Certificate Renewal

SSL certificates auto-renew, but monitor them:

# Check certificate expiration
sudo certbot certificates

# Test renewal process
sudo certbot renew --dry-run

# Manual renewal if needed
sudo certbot renew

3. Backup Configuration

Backup your configuration files:

# Nginx
sudo cp -r /etc/nginx/sites-available/ ~/nginx-backup-$(date +%Y%m%d)

# Apache
sudo cp -r /etc/apache2/sites-available/ ~/apache-backup-$(date +%Y%m%d)

πŸš€ Production Checklist

Before going live, verify:

  • DNS: Domain points to server IP
  • SSL: HTTPS certificate installed and valid
  • Security: Firewall configured, unnecessary ports blocked
  • Monitoring: Logs configured and health checks working
  • Performance: Caching enabled, compression configured
  • Backup: Configuration files backed up
  • Testing: All endpoints accessible via domain name
  • Documentation: Team knows configuration and maintenance procedures

πŸ“š Additional Resources


Next Steps: After setting up your reverse proxy, continue with the Security Guide to implement additional security measures for your production environment.

Clone this wiki locally