Apache
Chapter 66: Apache HTTP Server - Deep Dive
Section titled “Chapter 66: Apache HTTP Server - Deep Dive”Mastering Apache for Production Web Serving
Section titled “Mastering Apache for Production Web Serving”66.1 Understanding Apache Architecture
Section titled “66.1 Understanding Apache Architecture”What is Apache?
Section titled “What is Apache?”The Apache HTTP Server (httpd) is the world’s most widely used web server, known for its flexibility, power, and extensive module support. It follows a modular architecture where functionality is added through Dynamic Shared Objects (DSOs).
Apache Architecture+------------------------------------------------------------------+| || Apache HTTP Server || +-------------------------------------------------------------+ || | MPM (Multi-Processing Module) | || | +----------+ +----------+ +----------+ +----------+ | || | | prefork | | worker | | event | | kqueue | | || | +----------+ +----------+ +----------+ +----------+ | || | | | || +------------------------------+----------------------------------+ || | || +---------------------------+-----------------------------------+ || | Core Modules | || | +--------+ +--------+ +--------+ +--------+ +--------+ | || | | mod_php| |mod_ssl | |mod_rewrite| |mod_proxy| |mod_log| | || | +--------+ +--------+ +--------+ +--------+ +--------+ | || +-------------------------------------------------------------+ || | || +---------------------------+-----------------------------------+ || | Configuration Files | || | +-----------+ +---------------+ +---------------+ | || | | httpd.conf| | conf.d/*.conf| | sites-enabled/| | || | +-----------+ +---------------+ +---------------+ | || +-------------------------------------------------------------+ || |+------------------------------------------------------------------+MPM Comparison
Section titled “MPM Comparison” Apache MPM Comparison+------------------------------------------------------------------+| || prefork (Default on many distributions) || +----------------------------------------------------------+ || | - Pre-forks child processes before requests | || | - Each process handles one connection | || | - Best for: Non-thread-safe libraries (PHP) | || | - Memory: Higher (each process has own memory) | || | - Stability: Excellent (process isolation) | || +----------------------------------------------------------+ || || worker || +----------------------------------------------------------+ || | - Hybrid multi-process, multi-threaded | || | - Each process has multiple threads | || | - Better memory efficiency than prefork | || | - Best for: High concurrency | || +----------------------------------------------------------+ || || event (Default on modern Apache) || +----------------------------------------------------------+ || | - Based on worker, but optimizes keep-alive | || | - Dedicated thread handles keep-alive connections | || | - Best for: High traffic with persistent connections | || | - Recommended for modern workloads | || +----------------------------------------------------------+ || || Key Differences: || +----------------------------------------------------------+ || | MPM | Threading | Memory | Stability | Use Case | || | ------------|-----------|---------|-----------|------------| || | prefork | No | Higher | Best | PHP/mod_php | || | worker | Yes | Lower | Good | Mixed | || | event | Yes | Lowest | Good | High traffic| || +----------------------------------------------------------+ || |+------------------------------------------------------------------+66.2 Apache Installation and Configuration
Section titled “66.2 Apache Installation and Configuration”Installing Apache
Section titled “Installing Apache”# =============================================================================# ARCH LINUX# =============================================================================
# Install Apachesudo pacman -S apache
# Install with PHP (if needed)sudo pacman -S php php-apache
# Enable required modulessudo systemctl enable --now httpd
# =============================================================================# UBUNTU/DEBIAN# =============================================================================
# Install Apachesudo apt updatesudo apt install apache2
# Install modulessudo a2enmod ssl rewrite headers proxy proxy_fcgi
# Install PHP with FPMsudo apt install php-fpmsudo a2enmod proxy_fcgi setenvif
# Enable required sitessudo a2ensite default-sslsudo a2enmod php8.1-fpm
# Start Apachesudo systemctl enable --now apache2
# =============================================================================# RHEL/CENTOS# =============================================================================
# Install Apachesudo dnf install httpd
# Install PHPsudo dnf install php php-fpm
# Enable and startsudo systemctl enable --now httpd
# Configure firewallsudo firewall-cmd --permanent --add-service=httpsudo firewall-cmd --permanent --add-service=httpssudo firewall-cmd --reloadMain Configuration
Section titled “Main Configuration”# /etc/httpd/conf/httpd.conf (RHEL/CentOS)# /etc/apache2/apache2.conf (Debian/Ubuntu)
ServerRoot "/etc/httpd"Listen 80Listen 443
# Load essential modulesLoadModule mpm_event_module modules/mod_mpm_event.soLoadModule authz_core_module modules/mod_authz_core.soLoadModule log_config_module modules/mod_log_config.soLoadModule mime_module modules/mod_mime.soLoadModule dir_module modules/mod_dir.soLoadModule alias_module modules/mod_alias.so
# User/Group (RHEL)User apacheGroup apache
# Server settingsServerAdmin admin@example.comServerName server.example.com:80
# Document rootDocumentRoot "/var/www/html"
# Directory permissions<Directory /> AllowOverride none Require all denied</Directory>
<Directory "/var/www"> AllowOverride None Require all granted</Directory>
<Directory "/var/www/html"> Options Indexes FollowSymLinks AllowOverride None Require all granted</Directory>
# Default indexDirectoryIndex index.html
# LoggingErrorLog "logs/error_log"LogLevel warn
# MIME typesTypesConfig /etc/mime.types
# Include additional configsIncludeOptional conf.d/*.conf66.3 Virtual Hosts
Section titled “66.3 Virtual Hosts”Types of Virtual Hosts
Section titled “Types of Virtual Hosts” Virtual Host Types+------------------------------------------------------------------+| || Name-Based Virtual Hosting || +----------------------------------------------------------+ || | - Multiple websites on single IP address | || | - Based on Host header in request | || | - Most common configuration | || | - Requires DNS to point to same IP | || | | || | Example: | || | site1.example.com -> 192.168.1.10 | || | site2.example.com -> 192.168.1.10 | || +----------------------------------------------------------+ || || IP-Based Virtual Hosting || +----------------------------------------------------------+ || | - Each website has unique IP address | || | - Requires multiple IP addresses | || | - Used when SSL certificates need dedicated IPs | || | - Older method, less common today | || +----------------------------------------------------------+ || || Port-Based Virtual Hosting || +----------------------------------------------------------+ || | - Different websites on different ports | || | - Example: :80 and :8080 | || | - Less common for production | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+Virtual Host Configuration
Section titled “Virtual Host Configuration”# Name-based virtual host for HTTP<VirtualHost *:80> ServerName site1.example.com ServerAlias www.site1.example.com ServerAdmin admin@site1.example.com
DocumentRoot /var/www/site1/public_html
# Logging ErrorLog ${APACHE_LOG_DIR}/site1-error.log CustomLog ${APACHE_LOG_DIR}/site1-access.log combined
# Directory permissions <Directory /var/www/site1/public_html> Options -Indexes +FollowSymLinks AllowOverride All Require all granted </Directory>
# Security headers <IfModule mod_headers.c> Header always set X-Frame-Options "SAMEORIGIN" Header always set X-Content-Type-Options "nosniff" Header always set X-XSS-Protection "1; mode=block" </IfModule>
# Redirect to HTTPS Redirect permanent / https://site1.example.com/</VirtualHost>
# HTTPS virtual host<VirtualHost *:443> ServerName site1.example.com ServerAlias www.site1.example.com ServerAdmin admin@site1.example.com
DocumentRoot /var/www/site1/public_html
# SSL configuration SSLEngine on SSLCertificateFile /etc/ssl/certs/site1.crt SSLCertificateKeyFile /etc/ssl/private/site1.key SSLCertificateChainFile /etc/ssl/certs/site1-ca.crt
# SSL settings SSLProtocol all -SSLv2 -SSLv3 -TLSv1 -TLSv1.1 SSLHonorCipherOrder on SSLCipherSuite ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384
<Directory /var/www/site1/public_html> Options -Indexes +FollowSymLinks AllowOverride All Require all granted </Directory>
# Logging ErrorLog ${APACHE_LOG_DIR}/site1-ssl-error.log CustomLog ${APACHE_LOG_DIR}/site1-ssl-access.log combined</VirtualHost>66.4 Apache Modules
Section titled “66.4 Apache Modules”Essential Modules
Section titled “Essential Modules” Apache Modules Overview+------------------------------------------------------------------+| || Core Modules (Built-in) || +----------------------------------------------------------+ || | mod_core - Core functionality | || | mod_log_config - Logging | || | mod_mime - Content type detection | || | mod_dir - Directory index | || | mod_alias - URL redirection | || | mod_rewrite - URL rewriting | || +----------------------------------------------------------+ || || Common Modules (Enable with a2enmod) || +----------------------------------------------------------+ || | mod_ssl - SSL/TLS support | || | mod_php - PHP integration | || | mod_proxy - Proxy functionality | || | mod_proxy_fcgi - FastCGI proxy | || | mod_headers - HTTP headers manipulation | || | mod_expires - Cache control headers | || | mod_deflate - Compression (gzip) | || | mod_cache - Caching | || | mod_remoteip - IP anonymization | || +----------------------------------------------------------+ || || Security Modules || +----------------------------------------------------------+ || | mod_security - Web Application Firewall | || | mod_authz_core - Core authorization | || | mod_auth_basic - Basic authentication | || | mod_auth_digest - Digest authentication | || | mod_authn_file - File-based authentication | || | mod_authz_groupfile - Group authorization | || +----------------------------------------------------------+ || |+------------------------------------------------------------------+Module Commands
Section titled “Module Commands”# List enabled modules (Debian/Ubuntu)apache2ctl -Ma2query -m
# Enable modulesudo a2enmod sslsudo a2enmod rewritesudo a2enmod headerssudo a2enmod proxysudo a2enmod proxy_fcgi
# Disable modulesudo a2dismod sslsudo a2dismod php
# Check module statusapachectl -t -D DUMP_MODULES66.5 SSL/TLS Configuration
Section titled “66.5 SSL/TLS Configuration”SSL Configuration
Section titled “SSL Configuration”# SSL Virtual Host Configuration
<VirtualHost *:443> ServerName example.com
# Enable SSL SSLEngine on
# Certificate files SSLCertificateFile /etc/ssl/certs/server.crt SSLCertificateKeyFile /etc/ssl/private/server.key SSLCertificateChainFile /etc/ssl/certs/ca-bundle.crt
# Modern SSL configuration SSLProtocol all -SSLv2 -SSLv3 -TLSv1 -TLSv1.1 SSLHonorCipherOrder on
# Ciphers (Mozilla Intermediate) SSLCipherSuite ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384
# HSTS (HTTP Strict Transport Security) <IfModule mod_headers.c> Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" </IfModule>
# OCSP Stapling SSLUseStapling on SSLStaplingCache "shmcb:logs/ssl_stapling(32768)" SSLStaplingStandardCacheTimeout 3600 SSLStaplingErrorCacheTimeout 3600</VirtualHost>Generating SSL Certificates
Section titled “Generating SSL Certificates”# Self-signed certificate (for testing)sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 \ -keyout /etc/ssl/private/apache-selfsigned.key \ -out /etc/ssl/certs/apache-selfsigned.crt
# Generate CSR for CA-signed certificatesudo openssl req -new -newkey rsa:2048 -nodes \ -keyout server.key -out server.csr
# View certificate detailsopenssl x509 -in server.crt -text -nooutopenssl x509 -in server.crt -text -noout -certopt no_subject,no_header,no_version,no_serial,no_signame,no_validity,no_extensions,no_sigdump,no_aux
# Test SSL configurationopenssl s_client -connect example.com:443 -servername example.com66.6 Apache Performance Tuning
Section titled “66.6 Apache Performance Tuning”MPM Configuration
Section titled “MPM Configuration”<IfModule mpm_event_module> # StartServers: Number of child processes created at startup StartServers 4
# MinSpareServers: Minimum number of idle child processes MinSpareServers 10
# MaxSpareServers: Maximum number of idle child processes MaxSpareServers 20
# ServerLimit: Maximum configured value for MaxRequestWorkers ServerLimit 25
# MaxRequestWorkers: Maximum number of connections MaxRequestWorkers 25
# MaxConnectionsPerChild: Connections per child process MaxConnectionsPerChild 0 # 0 = unlimited</IfModule>
# For high-traffic servers:<IfModule mpm_event_module> StartServers 8 MinSpareThreads 25 MaxSpareThreads 75 ThreadLimit 64 ThreadsPerChild 25 MaxRequestWorkers 400 MaxConnectionsPerChild 0</IfModule>Compression and Caching
Section titled “Compression and Caching”# Enable compression<IfModule mod_deflate.c> AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/json
# Compression level DeflateCompressionLevel 6
# Don't compress images SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary</IfModule>
# Browser caching<IfModule mod_expires.c> ExpiresActive On ExpiresByType image/jpg "access plus 1 year" ExpiresByType image/jpeg "access plus 1 year" ExpiresByType image/gif "access plus 1 year" ExpiresByType image/png "access plus 1 year" ExpiresByType text/css "access plus 1 month" ExpiresByType application/javascript "access plus 1 month" ExpiresByType text/html "access plus 0 seconds"</IfModule>
# ETag<IfModule mod_headers.c> Header unset ETag</IfModule>FileETag None66.7 Security Best Practices
Section titled “66.7 Security Best Practices”Security Configuration
Section titled “Security Configuration”# Hide Apache versionServerTokens ProdServerSignature Off
# Disable directory listing<Directory /> Options -Indexes -FollowSymLinks AllowOverride None Require all denied</Directory>
# Protect sensitive files<FilesMatch "^\.ht"> Require all denied</FilesMatch>
<FilesMatch "\.(env|log|conf|ini|yml|yaml|md|gitignore|dockerignore)$"> Require all denied</FilesMatch>
# Prevent clickjacking<IfModule mod_headers.c> Header always set X-Frame-Options "SAMEORIGIN" Header always set X-Content-Type-Options "nosniff" Header always set X-XSS-Protection "1; mode=block" Header always set Referrer-Policy "strict-origin-when-cross-origin" Header always set Permissions-Policy "geolocation=(), microphone=(), camera=()"</IfModule>
# Rate limiting (if mod_ratelimit is enabled)<IfModule mod_ratelimit.c> SetOutputFilter RATE_LIMIT SetEnv rate-limit 4096</IfModule>
# Limit request size<Directory "/var/www/upload"> LimitRequestBody 10485760 # 10MB</Directory>
# TimeoutsTimeout 60KeepAlive OnMaxKeepAliveRequests 100KeepAliveTimeout 566.8 Common Apache Commands
Section titled “66.8 Common Apache Commands”Management Commands
Section titled “Management Commands”# Test configurationsudo apachectl configtestsudo apachectl -tsudo apache2ctl configtest
# Syntax checkapachectl -t -D DUMP_CONFIG
# Start/Stop/Restartsudo systemctl start apache2sudo systemctl stop apache2sudo systemctl restart apache2sudo systemctl reload apache2
# Graceful restart (reload without downtime)sudo apachectl gracefulsudo systemctl reload apache2
# Check statussudo systemctl status apache2
# List virtual hostsapache2ctl -Sapachectl -t -D VHOSTS
# Show compiled-in modulesapachectl -l
# Show loaded modulesapache2ctl -M66.9 Exam Tips
Section titled “66.9 Exam Tips”- MPM: Know the difference between prefork, worker, and event
- Virtual Hosts: Understand name-based vs IP-based
- Modules: Enable modules with a2enmod (Debian)
- SSL: Use modern protocols (TLS 1.2+) and ciphers
- Security: Hide version, set security headers
- Performance: Enable compression, configure caching
- Configuration: Always test with
apachectl configtest - Logging: Know where logs are stored
- .htaccess: Understand AllowOverride directives
- Rewrite: Use mod_rewrite for URL manipulation
Summary
Section titled “Summary”In this chapter, you learned:
- ✅ Apache architecture and MPM comparison
- ✅ Installation across distributions
- ✅ Virtual host configuration
- ✅ Module management
- ✅ SSL/TLS configuration
- ✅ Performance tuning
- ✅ Security best practices
- ✅ Common management commands
Next Chapter
Section titled “Next Chapter”Last Updated: February 2026