Apache HTTP Server: Complete Guide and Documentation
Table of Contents
1. [Introduction](#introduction) 2. [Installation](#installation) 3. [Configuration](#configuration) 4. [Virtual Hosts](#virtual-hosts) 5. [Security](#security) 6. [Performance Optimization](#performance-optimization) 7. [Modules](#modules) 8. [Log Management](#log-management) 9. [SSL/TLS Configuration](#ssltls-configuration) 10. [Troubleshooting](#troubleshooting) 11. [Commands Reference](#commands-reference)Introduction
Apache HTTP Server, commonly referred to as Apache, is one of the most widely used web servers in the world. Developed by the Apache Software Foundation, it is an open-source, cross-platform web server that has been serving web content since 1995. Apache is known for its flexibility, reliability, and extensive feature set.
Key Features
| Feature | Description | |---------|-------------| | Cross-platform | Runs on Unix, Linux, Windows, and macOS | | Modular Architecture | Extensible through modules | | Virtual Hosting | Multiple websites on single server | | URL Rewriting | Powerful URL manipulation | | SSL/TLS Support | Secure connections | | Authentication | Multiple authentication methods | | Compression | Content compression support | | Load Balancing | Distribution of requests |
Apache Architecture
Apache follows a modular architecture where core functionality is extended through modules. The server consists of:
- Core: Basic HTTP functionality - Multi-Processing Modules (MPMs): Handle connection processing - Standard Modules: Common functionality like authentication, SSL - Third-party Modules: Extended functionality
Installation
Linux (Ubuntu/Debian)
`bash
Update package repository
sudo apt updateInstall Apache
sudo apt install apache2Start Apache service
sudo systemctl start apache2Enable Apache to start on boot
sudo systemctl enable apache2Check Apache status
sudo systemctl status apache2`Linux (CentOS/RHEL/Fedora)
`bash
Install Apache (httpd package)
sudo yum install httpdor for newer versions
sudo dnf install httpdStart Apache service
sudo systemctl start httpdEnable Apache to start on boot
sudo systemctl enable httpdCheck Apache status
sudo systemctl status httpd`Windows
1. Download Apache from Apache Lounge or official Apache website 2. Extract files to desired directory (e.g., C:\Apache24) 3. Install as Windows service:
`cmd
Navigate to Apache bin directory
cd C:\Apache24\binInstall Apache as service
httpd.exe -k installStart Apache service
httpd.exe -k start`macOS
`bash
Using Homebrew
brew install httpdStart Apache
sudo brew services start httpd`Post-Installation Verification
After installation, verify Apache is running by accessing http://localhost in your browser. You should see the Apache default page.
Configuration
Apache configuration is managed through configuration files, with the main configuration file typically located at:
| Operating System | Main Config File |
|------------------|------------------|
| Ubuntu/Debian | /etc/apache2/apache2.conf |
| CentOS/RHEL | /etc/httpd/conf/httpd.conf |
| Windows | C:\Apache24\conf\httpd.conf |
| macOS | /usr/local/etc/httpd/httpd.conf |
Main Configuration Directives
#### Server Root and Document Root
`apache
Server root directory
ServerRoot "/etc/apache2"Document root - where web files are served from
DocumentRoot "/var/www/html"Directory permissions for document root
`#### Listen Directive
`apache
Listen on port 80 for all interfaces
Listen 80Listen on specific IP and port
Listen 192.168.1.100:80Listen on port 443 for SSL
Listen 443 ssl`#### Server Information
`apache
Server administrator email
ServerAdmin webmaster@example.comServer name (FQDN)
ServerName www.example.com:80Server tokens (security consideration)
ServerTokens Prod ServerSignature Off`Directory Configuration
Directory blocks control access and behavior for specific directories:
`apache
`
#### Options Directive Values
| Option | Description | |--------|-------------| | Indexes | Allow directory browsing | | FollowSymLinks | Follow symbolic links | | ExecCGI | Allow CGI execution | | Includes | Allow server-side includes | | MultiViews | Allow content negotiation | | None | No options enabled | | All | All options enabled |
#### AllowOverride Values
| Value | Description | |-------|-------------| | None | No .htaccess overrides allowed | | All | All overrides allowed | | AuthConfig | Authorization directives | | FileInfo | Document type directives | | Indexes | Directory indexing directives | | Limit | Access control directives |
Virtual Hosts
Virtual hosts allow Apache to serve multiple websites from a single server. There are two types:
Name-based Virtual Hosts
Multiple domains sharing the same IP address:
`apache
Enable name-based virtual hosting
NameVirtualHost *:80First virtual host
Second virtual host
`IP-based Virtual Hosts
Different IP addresses for different sites:
`apache
`
Virtual Host Best Practices
1. Create separate configuration files for each virtual host 2. Use descriptive log file names for easier troubleshooting 3. Set appropriate directory permissions 4. Include error pages for better user experience 5. Configure SSL for production sites
`apache
Example comprehensive virtual host
`Security
Basic Security Configuration
`apache
Hide Apache version
ServerTokens Prod ServerSignature OffDisable server-info and server-status
Prevent access to .htaccess files
Disable directory browsing globally
Options -IndexesPrevent access to sensitive files
`Authentication and Authorization
#### Basic Authentication
`apache
Create password file
htpasswd -c /etc/apache2/.htpasswd usernameConfigure authentication
`#### IP-based Access Control
`apache
Allow specific IP addresses
Deny specific IP addresses
`Security Headers
`apache
Load headers module
LoadModule headers_module modules/mod_headers.soSecurity headers
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=()"HSTS (HTTP Strict Transport Security)
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"`Performance Optimization
Multi-Processing Modules (MPMs)
Apache offers different MPMs for handling requests:
| MPM | Description | Best For | |-----|-------------|----------| | prefork | Process-based, one thread per process | PHP applications, maximum compatibility | | worker | Hybrid process/thread model | High-traffic sites with thread-safe applications | | event | Enhanced worker with better keep-alive handling | High-traffic sites, static content |
#### Prefork Configuration
`apache
`
#### Worker Configuration
`apache
`
#### Event Configuration
`apache
`
Compression
Enable compression to reduce bandwidth usage:
`apache
Load compression modules
LoadModule deflate_module modules/mod_deflate.soConfigure compression
Alternative configuration
`Caching
#### Browser Caching
`apache
Load expires module
LoadModule expires_module modules/mod_expires.soEnable expires
ExpiresActive OnSet default expiration
ExpiresDefault "access plus 1 month"Specific file types
ExpiresByType text/css "access plus 1 year" ExpiresByType application/javascript "access plus 1 year" ExpiresByType image/png "access plus 1 year" ExpiresByType image/jpg "access plus 1 year" ExpiresByType image/jpeg "access plus 1 year" ExpiresByType image/gif "access plus 1 year" ExpiresByType image/ico "access plus 1 year" ExpiresByType image/icon "access plus 1 year" ExpiresByType text/html "access plus 1 day"`#### Cache Control Headers
`apache
`
Modules
Loading Modules
`apache
Load module
LoadModule rewrite_module modules/mod_rewrite.soCheck if module is loaded
`Essential Modules
| Module | Purpose | Configuration |
|--------|---------|---------------|
| mod_rewrite | URL rewriting | LoadModule rewrite_module modules/mod_rewrite.so |
| mod_ssl | SSL/TLS support | LoadModule ssl_module modules/mod_ssl.so |
| mod_headers | HTTP headers | LoadModule headers_module modules/mod_headers.so |
| mod_deflate | Compression | LoadModule deflate_module modules/mod_deflate.so |
| mod_expires | Expiration headers | LoadModule expires_module modules/mod_expires.so |
URL Rewriting with mod_rewrite
`apache
Enable rewrite engine
RewriteEngine OnRedirect www to non-www
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L]Force HTTPS
RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]Pretty URLs
RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([^/]+)/?$ /profile.php?username=$1 [L,QSA]Remove file extensions
RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule (.*) $1.php [L]`Log Management
Log Files
| Log Type | Default Location (Ubuntu) | Default Location (CentOS) |
|----------|---------------------------|----------------------------|
| Access Log | /var/log/apache2/access.log | /var/log/httpd/access_log |
| Error Log | /var/log/apache2/error.log | /var/log/httpd/error_log |
Log Configuration
`apache
Error log configuration
ErrorLog "/var/log/apache2/error.log" LogLevel warnAccess log configuration
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %O" common LogFormat "%{Referer}i -> %U" referer LogFormat "%{User-agent}i" agentCustomLog "/var/log/apache2/access.log" combined
`
Custom Log Formats
`apache
Define custom log format
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %D" customUse custom format
CustomLog "/var/log/apache2/custom.log" customConditional logging
SetEnvIf Remote_Addr "127\.0\.0\.1" dontlog CustomLog "/var/log/apache2/access.log" combined env=!dontlog`Log Rotation
Create logrotate configuration:
`bash
Create logrotate configuration
sudo nano /etc/logrotate.d/apache2``
/var/log/apache2/*.log {
daily
missingok
rotate 52
compress
delaycompress
notifempty
create 640 root adm
sharedscripts
postrotate
if /bin/systemctl status apache2 > /dev/null ; then \
/bin/systemctl reload apache2 > /dev/null; \
fi;
endscript
}
`
SSL/TLS Configuration
Enabling SSL Module
`bash
Ubuntu/Debian
sudo a2enmod ssl sudo systemctl restart apache2CentOS/RHEL
SSL module is usually enabled by default
`SSL Virtual Host Configuration
`apache
`
SSL Security Configuration
`apache
Modern SSL configuration
SSLEngine on SSLProtocol all -SSLv2 -SSLv3 -TLSv1 -TLSv1.1 SSLCipherSuite ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384 SSLHonorCipherOrder on SSLCompression off SSLSessionTickets offOCSP Stapling
SSLUseStapling on SSLStaplingCache shmcb:/var/run/ocsp(128000)`Let's Encrypt Integration
`bash
Install Certbot
sudo apt install certbot python3-certbot-apacheObtain certificate
sudo certbot --apache -d example.com -d www.example.comTest automatic renewal
sudo certbot renew --dry-runSet up automatic renewal
echo "0 12 * /usr/bin/certbot renew --quiet" | sudo crontab -`Troubleshooting
Common Issues and Solutions
| Issue | Possible Cause | Solution | |-------|----------------|----------| | 403 Forbidden | Incorrect permissions | Check file/directory permissions | | 404 Not Found | Wrong DocumentRoot | Verify DocumentRoot setting | | 500 Internal Server Error | Configuration error | Check error logs | | Apache won't start | Port already in use | Check for conflicting services | | SSL certificate errors | Wrong certificate path | Verify certificate file paths |
Diagnostic Commands
`bash
Check Apache configuration syntax
sudo apache2ctl configtestor
sudo httpd -tCheck loaded modules
apache2ctl -Mor
httpd -MCheck virtual hosts
apache2ctl -Sor
httpd -SCheck Apache processes
ps aux | grep apacheor
ps aux | grep httpdCheck listening ports
sudo netstat -tlnp | grep :80 sudo netstat -tlnp | grep :443Test specific configuration
apache2ctl -t -D DUMP_VHOSTS`Log Analysis
`bash
Monitor error log in real-time
sudo tail -f /var/log/apache2/error.logSearch for specific errors
grep "Internal Server Error" /var/log/apache2/error.logAnalyze access patterns
awk '{print $1}' /var/log/apache2/access.log | sort | uniq -c | sort -nr | head -10Check for 404 errors
grep " 404 " /var/log/apache2/access.log`Commands Reference
Service Management
| Command | Description |
|---------|-------------|
| sudo systemctl start apache2 | Start Apache service |
| sudo systemctl stop apache2 | Stop Apache service |
| sudo systemctl restart apache2 | Restart Apache service |
| sudo systemctl reload apache2 | Reload configuration |
| sudo systemctl status apache2 | Check service status |
| sudo systemctl enable apache2 | Enable auto-start |
| sudo systemctl disable apache2 | Disable auto-start |
Configuration Management
`bash
Test configuration
sudo apache2ctl configtestGraceful restart
sudo apache2ctl gracefulShow compiled-in modules
apache2ctl -lShow loaded modules
apache2ctl -MShow virtual host settings
apache2ctl -SShow version information
apache2ctl -v`Site Management (Debian/Ubuntu)
`bash
Enable site
sudo a2ensite sitenameDisable site
sudo a2dissite sitenameEnable module
sudo a2enmod modulenameDisable module
sudo a2dismod modulenameList available sites
ls /etc/apache2/sites-available/List enabled sites
ls /etc/apache2/sites-enabled/`File and Directory Commands
`bash
Set proper ownership
sudo chown -R www-data:www-data /var/www/html/Set proper permissions for directories
find /var/www/html/ -type d -exec chmod 755 {} \;Set proper permissions for files
find /var/www/html/ -type f -exec chmod 644 {} \;Create .htaccess file
touch /var/www/html/.htaccessCreate password file
sudo htpasswd -c /etc/apache2/.htpasswd username`Performance Monitoring
`bash
Monitor server status (if mod_status enabled)
curl http://localhost/server-statusMonitor active connections
ss -tuln | grep :80Check memory usage
free -hMonitor Apache processes
top -p $(pgrep apache2 | tr '\n' ',' | sed 's/,$//')`Backup and Maintenance
`bash
Backup configuration
sudo tar -czf apache-config-backup-$(date +%Y%m%d).tar.gz /etc/apache2/Backup website files
sudo tar -czf website-backup-$(date +%Y%m%d).tar.gz /var/www/Rotate logs manually
sudo logrotate -f /etc/logrotate.d/apache2Clean old log files
find /var/log/apache2/ -name ".log." -mtime +30 -delete`This comprehensive guide covers the essential aspects of Apache HTTP Server configuration, management, and optimization. Regular monitoring, proper security configuration, and performance tuning are crucial for maintaining a robust web server environment. Always test configuration changes in a development environment before applying them to production servers.