28. Web Servers & Reverse Proxy
Web servers and reverse proxies form the entry point of modern infrastructure. An origin web server executes application logic and serves static assets, while a reverse proxy sits in front to terminate TLS encryption, distribute traffic across application replicas, enforce security policies, and prevent single-point bottlenecks.
28.1 Web Server vs Reverse Proxy vs Forward Proxy
Section titled “28.1 Web Server vs Reverse Proxy vs Forward Proxy”Understanding the direction of network traffic and the role of each component is essential for infrastructure architecture:
Forward Proxy (Protects/Proxies Clients): Internal Clients (Users) ──► Forward Proxy (e.g. Squid) ──► Internet Web Servers
Reverse Proxy (Protects/Proxies Servers): Internet Clients (Users) ──► Reverse Proxy (e.g. Nginx) ──► Internal Application Backends
Origin Web Server (Serves Content / Logic): Reverse Proxy (Nginx) ──► Web Server (Apache httpd) ──► PHP-FPM / Local Storage- Origin Web Server (e.g., Apache HTTP Server, Nginx standalone): Accepts HTTP requests, parses configuration directives, reads files from disk (
/var/www/html), runs application runtimes (PHP, Python WSGI, CGI), and returns HTTP responses. - Reverse Proxy (e.g., Nginx, HAProxy, Envoy, Traefik): Sits in front of origin servers or microservice backends. Clients connect to the proxy, which routes requests to backend servers, shields private IP topology, caches responses, and offloads TLS processing.
- Forward Proxy (e.g., Squid): Sits on the client side. Intercepts outbound user requests to enforce corporate egress filtering, scan for malware, or cache remote web pages.
28.2 Apache HTTP Server on RHEL & Ubuntu
Section titled “28.2 Apache HTTP Server on RHEL & Ubuntu”Apache (httpd / apache2) remains one of the most widely deployed open-source web servers, featuring modular architecture (mod_rewrite, mod_ssl, mod_proxy) and robust .htaccess support.
Apache on RHEL / AlmaLinux / Rocky
Section titled “Apache on RHEL / AlmaLinux / Rocky”In Red Hat ecosystems, Apache is packaged as httpd.
1. Installation and Service Setup
Section titled “1. Installation and Service Setup”# Install Apache and SSL modulesudo dnf install httpd mod_ssl -y
# Enable and start the servicesudo systemctl enable --now httpdsudo systemctl status httpd2. Firewall Configuration
Section titled “2. Firewall Configuration”sudo firewall-cmd --permanent --add-service=httpsudo firewall-cmd --permanent --add-service=httpssudo firewall-cmd --reload3. SELinux Contexts
Section titled “3. SELinux Contexts”RHEL enforces strict SELinux labels on web directory contents. The default document root /var/www/html/ carries the label httpd_sys_content_t.
If you host sites in custom directories (e.g., /srv/www or /var/www/app), you must set the correct SELinux context:
# Register persistent SELinux context for the custom pathsudo semanage fcontext -a -t httpd_sys_content_t "/var/www/custom(/.*)?"
# Apply the context recursivelysudo restorecon -Rv /var/www/custom
# If Apache must initiate outbound network connections (reverse proxying or database sockets)sudo setsebool -P httpd_can_network_connect 14. Virtual Host Configuration (/etc/httpd/conf.d/app.example.com.conf)
Section titled “4. Virtual Host Configuration (/etc/httpd/conf.d/app.example.com.conf)”<VirtualHost *:80> ServerName app.example.com ServerAlias www.app.example.com DocumentRoot /var/www/html/app
ErrorLog /var/log/httpd/app_error.log CustomLog /var/log/httpd/app_access.log combined
<Directory /var/www/html/app> Options -Indexes +FollowSymLinks AllowOverride All Require all granted </Directory></VirtualHost>Apache on Ubuntu / Debian
Section titled “Apache on Ubuntu / Debian”In Debian and Ubuntu ecosystems, Apache is packaged as apache2 and uses utility scripts (a2ensite, a2enmod) to manage configurations.
1. Installation and Service Setup
Section titled “1. Installation and Service Setup”sudo apt updatesudo apt install apache2 -ysudo systemctl enable --now apache2sudo systemctl status apache22. Firewall Configuration (UFW)
Section titled “2. Firewall Configuration (UFW)”sudo ufw allow 'Apache Full'sudo ufw status3. Directory Layout and Management Utilities
Section titled “3. Directory Layout and Management Utilities”- Configuration files: Stored in
/etc/apache2/sites-available/ - Active sites: Symlinked into
/etc/apache2/sites-enabled/ - Site management:
Terminal window # Enable or disable a virtual hostsudo a2ensite app.example.com.confsudo a2dissite 000-default.conf# Enable required Apache modulessudo a2enmod rewrite ssl headers proxy proxy_http# Validate configuration syntaxsudo apache2ctl configtest# Gracefully reloadsudo systemctl reload apache2
4. Virtual Host & TLS Configuration with Let’s Encrypt
Section titled “4. Virtual Host & TLS Configuration with Let’s Encrypt”# Install Certbot for Apachesudo apt install certbot python3-certbot-apache -y
# Obtain and install SSL certificates automaticallysudo certbot --apache -d app.example.com -d www.app.example.comCertbot automatically configures the SSL virtual host block (/etc/apache2/sites-available/app.example.com-le-ssl.conf) with modern TLS parameters and sets up automated renewal timers via certbot.timer.
28.3 Nginx Reverse Proxy Architecture
Section titled “28.3 Nginx Reverse Proxy Architecture”Deploying Nginx as an edge reverse proxy in front of backend microservices or Apache web servers provides high throughput, low memory footprint (event-driven asynchronous worker model), and seamless TLS termination:
Internet / Clients │ (HTTPS :443) ┌────────────────┐ │ Nginx Ingress │ <-- TLS Termination, Rate Limiting, Caching └───────┬────────┘ │ (Internal HTTP / Unix Socket) ┌────────────┼────────────┐ │ │ │ ┌────────────┐┌────────────┐┌────────────┐ │ App Node 1 ││ App Node 2 ││ App Node 3 │ │ (:3001) ││ (:3002) ││ (:3003) │ └────────────┘└────────────┘└────────────┘Key Architectural Benefits
Section titled “Key Architectural Benefits”- Single Entry Point: External clients connect to one public IP and domain, regardless of how many microservices run internally.
- TLS / SSL Termination: The reverse proxy decrypts incoming HTTPS traffic, offloading cryptographic CPU overhead from backend apps.
- High Availability: If
App Node 2crashes, the reverse proxy detects the failure and routes all traffic toApp Node 1andApp Node 3. - Security Isolation: Shields backend server topology, private IP addresses, and runtime framework headers.
28.4 Basic Nginx Reverse Proxy Configuration
Section titled “28.4 Basic Nginx Reverse Proxy Configuration”A minimal configuration to forward public traffic on port 80 to a local Node.js, Go, or Python backend running on port 3000:
server { listen 80; server_name api.example.com;
location / { # Forward the request to the internal backend proxy_pass http://127.0.0.1:3000;
# Preserve client headers (CRITICAL for logging & security) 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;
# WebSockets support proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; }}[!IMPORTANT] If you do not pass
X-Real-IPandX-Forwarded-For, your backend application logs will show127.0.0.1as the source IP for every user on the internet!
28.5 Load Balancing with Upstream Pools
Section titled “28.5 Load Balancing with Upstream Pools”To distribute traffic across multiple application instances, use the upstream block in Nginx:
# Define the pool of backend application serversupstream backend_cluster { server 10.0.0.11:3000 weight=3; # Handles 3x more traffic server 10.0.0.12:3000; server 10.0.0.13:3000 backup; # Only receives traffic if primary nodes fail}
server { listen 80; server_name app.example.com;
location / { proxy_pass http://backend_cluster; 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; }}Load Balancing Algorithms
Section titled “Load Balancing Algorithms”Nginx supports several load distribution algorithms:
1. Round Robin (Default)
Section titled “1. Round Robin (Default)”Requests are distributed evenly in sequential rotation across all upstream servers:
upstream backend { server app1.internal:8080; server app2.internal:8080;}2. Weighted Round Robin
Section titled “2. Weighted Round Robin”Directs more requests to servers with higher capacity using the weight parameter:
upstream backend { server app1.internal:8080 weight=2; # Receives 2 out of every 3 requests server app2.internal:8080 weight=1;}3. Least Connections (least_conn)
Section titled “3. Least Connections (least_conn)”Sends new requests to the server with the fewest active open connections. Ideal for long-running transactions (file uploads, heavy database queries):
upstream backend { least_conn; server app1.internal:8080; server app2.internal:8080;}4. IP Hash (ip_hash)
Section titled “4. IP Hash (ip_hash)”Computes a hash of the client’s IPv4 address to consistently route that client to the same backend server (Session Persistence / Sticky Sessions):
upstream backend { ip_hash; server app1.internal:8080; server app2.internal:8080;}28.6 Health Checks & Failover
Section titled “28.6 Health Checks & Failover”Nginx open-source handles passive health checks automatically via max_fails and fail_timeout:
upstream backend { # If a server fails 3 times in 10 seconds, mark it inactive for 30 seconds server 10.0.0.11:3000 max_fails=3 fail_timeout=30s; server 10.0.0.12:3000 max_fails=3 fail_timeout=30s; server 10.0.0.13:3000 max_fails=3 fail_timeout=30s;}Fast Timeout Handling
Section titled “Fast Timeout Handling”Prevent slow or unresponsive backends from holding connections open:
location / { proxy_pass http://backend;
# Timeouts for connecting and reading from upstream proxy_connect_timeout 3s; proxy_read_timeout 10s; proxy_send_timeout 10s;
# Immediately retry next server if current node returns 502/503/504 proxy_next_upstream error timeout invalid_header http_502 http_503 http_504;}28.7 TLS / SSL Termination & Security Headers
Section titled “28.7 TLS / SSL Termination & Security Headers”Terminating TLS at Nginx centralizes certificate management, allowing you to renew certificates in one place (e.g., with Let’s Encrypt / Certbot) while backend apps communicate in fast, unencrypted HTTP over a private VPC network:
server { listen 80; server_name example.com www.example.com; # Redirect all HTTP requests to HTTPS return 301 https://$host$request_uri;}
server { listen 443 ssl http2; server_name example.com www.example.com;
# SSL Certificates ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# Modern SSL Protocols & Ciphers ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; ssl_session_cache shared:SSL:10m; ssl_session_timeout 1d;
# Enterprise Security Headers add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; add_header X-Content-Type-Options nosniff; add_header X-Frame-Options DENY; add_header X-XSS-Protection "1; mode=block";
location / { proxy_pass http://backend_cluster; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto https; }}28.8 Testing, Reloading & Troubleshooting
Section titled “28.8 Testing, Reloading & Troubleshooting”Never reload a web server or reverse proxy in production without verifying syntax:
# Test Nginx syntaxsudo nginx -t
# Gracefully reload Nginx without dropping active client connectionssudo systemctl reload nginx
# Test Apache syntaxsudo apachectl configtest # RHEL (httpd)sudo apache2ctl configtest # Ubuntu (apache2)
# Gracefully reload Apachesudo systemctl reload httpd # RHELsudo systemctl reload apache2 # UbuntuCommon HTTP Proxy Status Codes & Diagnostics
Section titled “Common HTTP Proxy Status Codes & Diagnostics”- 502 Bad Gateway: Nginx received an invalid response or connection reset from the upstream application (backend service is down, crashing on start, or not listening on specified port).
- 504 Gateway Timeout: Upstream application took longer to respond than
proxy_read_timeout(database slow query, external API bottleneck, application deadlock). - 500 Internal Server Error: Origin application generated an unhandled exception or Nginx internal file permission error.