Network and System AdministrationUnit 716 min read
Web Server Configuration: Apache vs Nginx, Virtual Hosts, Modules, Security
Unit 7 of Network and System Administration covers configuring Apache and Nginx web servers, including virtual hosting, module management, security hardening, performance tuning, and real-world deployment scenarios. Learn how to set up, monitor, and optimize servers for high availability and scalability.
TAKEAWAYS:
- Apache and Nginx differ in architecture (process vs event-driven), use cases (static vs dynamic content), and configuration files (
.confvs.nginx). - Virtual hosts enable a single server to host multiple websites using either name-based or IP-based configurations.
- Security best practices include disabling unused modules, enforcing HTTPS, and restricting directory access.
- Performance tuning involves adjusting worker processes, caching, and load balancing for optimal resource usage.
- Real-world applications include eSewa’s payment gateway (Nginx for high concurrency) and Daraz’s product catalog (Apache for PHP compatibility).
Apache and Nginx: Core Concepts and Architecture
1. What Are Apache and Nginx?
Apache and Nginx are the two most widely used web servers globally. A web server is software that processes HTTP requests, delivers static/dynamic content, and manages server resources. They act as the front door for websites, handling everything from file requests to SSL encryption.
sequenceDiagram
participant Client
participant Apache
participant PHP
participant Database
Client->>Apache: GET /index.php
Apache->>PHP: Spawns process (mod_php)
PHP->>Database: Query
Database-->>PHP: Result
PHP-->>Apache: HTML
Apache-->>Client: Response
participant Client
participant Nginx
participant Node.js
participant Database
Client->>Nginx: GET /api
Nginx->>Node.js: proxy_pass
Node.js->>Database: Query
Database-->>Node.js: Result
Node.js-->>Nginx: JSON
Nginx-->>Client: ResponseApache (process-based) vs Nginx (reverse proxy) request handling flowKey Differences
| Feature | Apache (httpd) | Nginx |
|---|---|---|
| Architecture | Process-based (multi-processing) | Event-driven (asynchronous, non-blocking) |
| Performance | Slower under high concurrency (~10K req/s) | Faster (~100K+ req/s) |
| Static Content | Good (mod_rewrite, .htaccess) | Excellent (low overhead) |
| Dynamic Content | Strong (PHP, Python via mod_php/mod_wsgi) | Requires reverse proxy (e.g., FastCGI) |
| Configuration | .conf files (modular) |
.nginx files (directive-based) |
| Use Case | Shared hosting, legacy PHP apps | High-traffic sites (e.g., Netflix, Dropbox) |
| Module Support | Extensive (mod_security, mod_ssl) | Limited (dynamic modules via ngx_http_*) |
How They Work Internally
Apache:
- Uses a prefork MPM (Multi-Processing Module) by default, where each request spawns a new process (resource-intensive).
- Supports worker MPM (threaded) for better performance but requires careful tuning.
- Relies on modules (e.g.,
mod_ssl,mod_php) for extended functionality.
Nginx:
- Uses a single master process and worker processes (non-blocking I/O).
- Handles requests asynchronously, making it ideal for high concurrency.
- Acts as a reverse proxy for dynamic content (e.g., forwarding requests to Node.js/Python).
2. Installing Apache and Nginx on Linux
Installation Steps (Ubuntu/Debian)
# Apache
sudo apt update
sudo apt install apache2
sudo systemctl start apache2
sudo systemctl enable apache2
# Nginx
sudo apt install nginx
sudo systemctl start nginx
sudo systemctl enable nginx
Verify Installation
- Apache: Visit
http://localhostor check status:sudo systemctl status apache2 - Nginx: Check running processes:
ps aux | grep nginx
Configuring Apache: Virtual Hosts and Modules
1. Virtual Hosts: Hosting Multiple Websites
Virtual hosts allow a single server to host multiple websites using either:
- Name-based (same IP, different domain names, e.g.,
example.com,test.example.com). - IP-based (different IPs for each site, less common today).
Example: Name-Based Virtual Host for example.com and blog.example.com
- Create directory structure:
sudo mkdir -p /var/www/example.com/public_html sudo mkdir -p /var/www/blog.example.com/public_html - Configure Apache (
/etc/apache2/sites-available/):# /etc/apache2/sites-available/example.com.conf <VirtualHost *:80> ServerName example.com ServerAlias www.example.com DocumentRoot /var/www/example.com/public_html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> # /etc/apache2/sites-available/blog.example.com.conf <VirtualHost *:80> ServerName blog.example.com DocumentRoot /var/www/blog.example.com/public_html ErrorLog ${APACHE_LOG_DIR}/blog_error.log CustomLog ${APACHE_LOG_DIR}/blog_access.log combined </VirtualHost> - Enable sites and restart Apache:
sudo a2ensite example.com.conf blog.example.com.conf sudo systemctl restart apache2
Worked Example: eSewa’s Payment Gateway
eSewa uses Apache with virtual hosts to separate:
esewa.com.np(public portal, static content).api.esewa.com.np(dynamic backend, PHP-based).- Why Apache? Compatibility with legacy PHP applications and
.htaccessfor URL rewriting.
2. Managing Apache Modules
Apache’s power comes from modules (.so files). Key modules:
Enable/Disable Modules
# Enable mod_ssl (for HTTPS)
sudo a2enmod ssl
sudo systemctl restart apache2
# Disable mod_autoindex (security risk)
sudo a2dismod autoindex
sudo systemctl restart apache2
Security Hardening
- Disable unused modules (e.g.,
mod_status,mod_info). - Restrict directory listing:
<Directory /var/www/> Options -Indexes AllowOverride None </Directory> - Use
.htaccessfor per-directory rules (but avoid overuse for performance).
Configuring Nginx: Performance and Reverse Proxy
1. Nginx Configuration Basics
Nginx uses directives in /etc/nginx/nginx.conf and site configs in /etc/nginx/sites-available/.
Example: Basic Nginx Server Block
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html index.htm;
```figure
{"type":"fields","width":32,"rows":[[{"label":"server {","bits":1}],[{"label":" listen 80;","bits":1}],[{"label":" server_name example.com;","bits":1}],[{"label":" root /var/www/html;","bits":1}],[{"label":" index index.html;","bits":1}],[{"label":"}","bits":1}]],"caption":"Nginx server block structure (minimal viable config)"}
location / {
try_files $uri $uri/ =404;
}
location /images/ {
expires 30d;
access_log off;
}
}
Key Directives
| Directive | Purpose |
|---|---|
listen |
Port to listen on (e.g., 80, 443). |
server_name |
Domain name for this block. |
root |
Root directory for files. |
index |
Default file to serve (e.g., index.html). |
location |
URL matching and routing. |
proxy_pass |
Forward requests to backend (e.g., Node.js). |
2. Nginx as a Reverse Proxy for Dynamic Content
Nginx excels at offloading static content while proxying dynamic requests to apps like Node.js, Python (Flask/Django), or PHP-FPM.
Example: Proxying to a Node.js App
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://localhost:3000; # Node.js app
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
Worked Example: Pathao’s Ride-Hailing API
Pathao uses Nginx as a reverse proxy to:
- Serve static assets (e.g.,
/css/,/js/) directly from Nginx. - Proxy API requests (e.g.,
/api/orders) to a Node.js backend. - Why Nginx? Handles 100K+ concurrent connections efficiently.
3. Performance Tuning
Worker Processes and Connections
Nginx’s nginx.conf controls worker processes:
worker_processes auto; # Auto-detect CPU cores
events {
worker_connections 1024; # Max connections per worker
}
- Rule of thumb:
worker_connections = 2 * max_clients_per_worker.
Caching Static Content
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m;
server {
location /static/ {
proxy_cache my_cache;
proxy_pass http://backend;
}
}
Load Balancing
upstream backend {
server 192.168.1.10:3000;
server 192.168.1.11:3000;
server 192.168.1.12:3000;
}
server {
location / {
proxy_pass http://backend;
}
}
Security Best Practices for Both Servers
1. Common Threats and Mitigations
| Threat | Apache Fix | Nginx Fix |
|---|---|---|
| SQL Injection | Use mod_security rules |
Block malicious queries in location |
| DDoS | Rate limiting (mod_evasive) |
limit_req_zone |
| XSS | mod_headers (CSP headers) |
add_header Content-Security-Policy |
| Brute Force | Fail2Ban + mod_authz_host |
deny IP ranges in server block |
2. Enforcing HTTPS
Apache (Let’s Encrypt)
sudo apt install certbot python3-certbot-apache
sudo certbot --apache -d example.com
Nginx (Let’s Encrypt)
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d example.com
Worked Example: Daraz’s HTTPS Enforcement
Daraz uses Nginx + Let’s Encrypt to:
- Redirect all HTTP → HTTPS.
- Use HSTS headers to prevent downgrade attacks.
- Result: 99% of traffic is encrypted.
Monitoring and Logging
1. Apache Logs
- Access Log:
/var/log/apache2/access.logLogFormat "%h %l %u %t \"%r\" %>s %b" combined - Error Log:
/var/log/apache2/error.log- Check for
404,500errors.
- Check for
2. Nginx Logs
- Access Log:
/var/log/nginx/access.logaccess_log /var/log/nginx/access.log combined; - Error Log:
/var/log/nginx/error.log- Use
tail -ffor real-time monitoring:tail -f /var/log/nginx/error.log
- Use
3. Tools for Monitoring
| Tool | Purpose | Command |
|---|---|---|
htop |
Real-time process monitoring | htop |
netstat |
Active connections | netstat -tulnp |
nginx -t |
Test Nginx config | sudo nginx -t |
apache2ctl |
Apache config test | sudo apache2ctl configtest |
fail2ban |
Block brute-force attacks | sudo systemctl status fail2ban |
In the Real World
eSewa (Nepal):
- Uses Apache for its PHP-based payment gateway (
esewa.com.np). - Why Apache? Legacy PHP compatibility and
.htaccessfor URL rewriting (e.g.,/pay?amount=1000→/payment/1000/). - Security:
mod_securityblocks SQLi/XSS; rate limiting prevents DoS.
- Uses Apache for its PHP-based payment gateway (
Pathao (Global):
- Nginx handles 10M+ daily requests for ride-hailing APIs.
- Architecture:
- Static assets (maps, CSS) served by Nginx.
- Dynamic API calls proxied to Node.js microservices.
- Performance:
worker_processes 4(4 CPU cores);worker_connections 4096.
NTC (Nepal Telecom):
- Uses Apache + mod_proxy to load-balance traffic across data centers.
- Example: When you visit
ntc.net.np, requests are routed via:- Nginx (static content:
/images/,/css/). - Apache (dynamic:
/login,/billing).
- Nginx (static content:
NEPSE (Nepal Stock Exchange):
- Nginx + HAProxy for high availability during trading hours.
- Security: Strict CORS policies, IP whitelisting for
/api/trades.
Exam Tip
What Examiners Look For
Configuration Files:
- Show correct syntax for virtual hosts (Apache) or
serverblocks (Nginx). - Example: A name-based virtual host with
ServerName,DocumentRoot, andErrorLogdirectives.
- Show correct syntax for virtual hosts (Apache) or
Performance vs Security Trade-offs:
- Apache: "Disable
mod_autoindexto prevent directory listing attacks." - Nginx: "Use
proxy_cacheto reduce backend load but ensureinactive=60mdoesn’t stale data."
- Apache: "Disable
Real-World Scenarios:
- eSewa: "Apache is used because of PHP compatibility and
.htaccessfor URL rewriting." - Pathao: "Nginx’s event-driven model handles 100K+ concurrent API calls efficiently."
- eSewa: "Apache is used because of PHP compatibility and
Troubleshooting:
- Apache error:
500 Internal Server Error→ Check/var/log/apache2/error.logfor PHP syntax errors. - Nginx error:
502 Bad Gateway→ Backend service (e.g., Node.js) is down; checksystemctl status nodejs.
- Apache error:
Common Pitfalls:
- Forgetting to enable a site (
a2ensitefor Apache). - Missing semicolons in Nginx configs.
- Overlapping
locationblocks (specific rules should come before general ones).
- Forgetting to enable a site (
Sample Exam Questions and Answers
Q1: Explain how you would configure Apache to host two websites, example.com and blog.example.com, using name-based virtual hosts.
Answer:
- Create directories:
sudo mkdir -p /var/www/example.com/public_html sudo mkdir -p /var/www/blog.example.com/public_html - Configure
/etc/apache2/sites-available/example.com.confandblog.example.com.confwithServerNameandDocumentRoot. - Enable sites:
sudo a2ensite example.com.conf blog.example.com.conf sudo systemctl restart apache2 - Verify: Access
http://example.comandhttp://blog.example.comin browsers.
Q2: Why would Pathao choose Nginx over Apache for its ride-hailing API?
Answer:
- Concurrency: Nginx’s event-driven architecture handles 100K+ concurrent API calls (e.g.,
/api/orders) without spawning new processes. - Reverse Proxy: Nginx efficiently forwards dynamic requests to Node.js backend while serving static assets (maps, CSS) directly.
- Performance: Lower memory usage than Apache’s prefork MPM under high load.
Q3: How would you secure an Nginx server against DDoS attacks?
Answer:
- Rate Limiting:
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s; server { location /api/ { limit_req zone=one burst=20; } } - Block Bad Bots:
location / { deny 192.168.1.100; # Known malicious IP allow all; } - Use Fail2Ban:
sudo apt install fail2ban sudo systemctl enable fail2ban
Final Checklist Before Exam
- Know the difference between Apache’s MPM (prefork/worker) and Nginx’s event-driven model.
- Memorize key directives for virtual hosts (
ServerName,DocumentRoot) and Nginx blocks (listen,proxy_pass). - Understand security hardening (HTTPS,
mod_security, rate limiting). - Practice configuring and testing both servers on a VM (e.g., VirtualBox).
- Relate concepts to real-world examples (eSewa, Pathao, NTC).
Based on the TU BIT syllabus for Network and System Administration (BIT451), unit 7.
Discussion
Loading…