Introduction
Apache HTTP Server (Apache) is the world’s most widely used web server software, powering approximately 25% of all active websites on the internet. It’s an open-source, cross-platform software that handles HTTP requests and serves web content. Apache’s popularity stems from its reliability, flexibility, and extensive feature set through its modular architecture.
Core Concepts
| Concept | Description |
|---|---|
| Virtual Hosts | Allow a single Apache instance to serve multiple websites |
| Directives | Configuration commands that control Apache’s behavior |
| Modules | Extensions that add functionality to the core server |
| Configuration Files | Text files containing directives that configure the server |
| Directory Context | Sections in configuration files that apply settings to specific directories |
Essential Configuration Files
| File/Directory | Purpose |
|---|---|
/etc/apache2/ or /etc/httpd/ | Main configuration directory |
apache2.conf or httpd.conf | Main configuration file |
sites-available/ | Directory containing available virtual host configurations |
sites-enabled/ | Directory containing enabled virtual host configurations (symlinks) |
mods-available/ | Directory containing available module configurations |
mods-enabled/ | Directory containing enabled module configurations (symlinks) |
.htaccess | Directory-level configuration file for overriding server settings |
Basic Apache Configuration Directives
Server Settings
# Server identification
ServerName example.com
ServerAdmin webmaster@example.com
ServerTokens Prod
ServerSignature Off
# Performance settings
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
Directory Access Control
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
<Directory /private>
Options None
AllowOverride None
Require all denied
</Directory>
Virtual Host Configuration
<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/example.com
ErrorLog ${APACHE_LOG_DIR}/example.com_error.log
CustomLog ${APACHE_LOG_DIR}/example.com_access.log combined
</VirtualHost>
Understanding Apache Options
| Option | Description |
|---|---|
Indexes | Allows directory listing when no index file exists |
FollowSymLinks | Allows Apache to follow symbolic links |
SymLinksIfOwnerMatch | Follows symbolic links only if owner matches |
ExecCGI | Allows execution of CGI scripts |
MultiViews | Enables content negotiation |
All | Enables all options except MultiViews |
None | Disables all options |
AllowOverride Settings
| Setting | Description |
|---|---|
All | Allow all .htaccess directives |
None | Disable .htaccess completely |
AuthConfig | Allow authentication directives |
FileInfo | Allow directives controlling document types |
Indexes | Allow directives controlling directory indexing |
Limit | Allow directives controlling host access |
Options[=Option,...] | Allow directives controlling specific options |
Security Configurations
Restricting Access
# By IP
<Directory /protected>
Require ip 192.168.1.0/24
</Directory>
# By hostname
<Directory /protected>
Require host example.org
</Directory>
# Basic Authentication
<Directory /protected>
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /etc/apache2/.htpasswd
Require valid-user
</Directory>
SSL Configuration
<VirtualHost *:443>
ServerName example.com
DocumentRoot /var/www/example.com
SSLEngine on
SSLCertificateFile /path/to/certificate.crt
SSLCertificateKeyFile /path/to/private.key
SSLCertificateChainFile /path/to/chain.crt
# Strong SSL settings
SSLProtocol all -SSLv2 -SSLv3 -TLSv1 -TLSv1.1
SSLCipherSuite HIGH:!aNULL:!MD5:!3DES
SSLHonorCipherOrder on
Header always set Strict-Transport-Security "max-age=63072000; includeSubdomains; preload"
</VirtualHost>
Rewrite Rules and URL Manipulation
Enable Rewrite Module
sudo a2enmod rewrite
sudo systemctl restart apache2
Common Rewrite Rules
# Force HTTPS
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# www to non-www
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
# Clean URLs
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^([^/]+)/([^/]+)/?$ index.php?category=$1&item=$2 [NC,L]
Performance Optimization
Caching Directives
# Enable 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"
ExpiresDefault "access plus 2 days"
</IfModule>
# Enable compression
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/x-javascript application/json
</IfModule>
MPM Configuration
# Prefork MPM (stable, compatible)
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150
MaxConnectionsPerChild 0
</IfModule>
# Worker MPM (threaded)
<IfModule mpm_worker_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 0
</IfModule>
# Event MPM (best performance for HTTP/1.1)
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 0
</IfModule>
Common Challenges and Solutions
| Challenge | Solution |
|---|---|
| 403 Forbidden errors | Check directory permissions; ensure Apache user can access files (usually www-data) |
| 500 Internal Server errors | Check Apache error logs; verify syntax in configuration files and .htaccess |
| Slow performance | Enable caching, compression; optimize MPM settings; monitor resource usage |
| Cannot override settings with .htaccess | Ensure AllowOverride is set to All or appropriate value |
| SSL certificate issues | Verify certificate paths and permissions; check certificate chain order |
| Rewrite rules not working | Ensure mod_rewrite is enabled; check RewriteBase directive; use [L] flag |
Command-Line Tools
Apache Control Commands
# Ubuntu/Debian
sudo systemctl start apache2
sudo systemctl stop apache2
sudo systemctl restart apache2
sudo systemctl reload apache2
sudo systemctl status apache2
# CentOS/RHEL
sudo systemctl start httpd
sudo systemctl stop httpd
sudo systemctl restart httpd
sudo systemctl reload httpd
sudo systemctl status httpd
Managing Modules
# Ubuntu/Debian
sudo a2enmod module_name # Enable a module
sudo a2dismod module_name # Disable a module
# CentOS/RHEL
sudo yum install mod_modulename # Install a module
Managing Virtual Hosts
# Ubuntu/Debian
sudo a2ensite site_name.conf # Enable a site
sudo a2dissite site_name.conf # Disable a site
Testing Configuration
# Check configuration syntax
sudo apachectl configtest
# or
sudo apache2ctl -t
# Show compiled modules
apache2ctl -M
Best Practices
Security
- Hide server information using
ServerTokens ProdandServerSignature Off - Implement strong SSL/TLS settings and enforce HTTPS
- Restrict directory access using appropriate
Requiredirectives - Regularly update Apache and all modules
- Hide server information using
Performance
- Enable caching for static assets
- Configure compression for text-based content
- Choose appropriate MPM based on workload
- Monitor and tune MaxRequestWorkers based on available memory
Maintenance
- Use separate configuration files for virtual hosts
- Store site-specific configurations in virtual host files, not .htaccess
- Document configuration changes
- Implement proper logging and monitoring
- Back up configuration files before making changes
Organization
- Use the Include directive to organize configuration into logical files
- Maintain a consistent naming convention for virtual hosts
- Comment configurations adequately
