📖 Guide
Apache — Complete Reference
Complete Apache HTTP Server cheat sheet — virtual hosts, modules, rewrite rules, and SSL.
76 commands across 10 categories
Service ManagementConfiguration FilesVirtual HostsModulesRewrite RulesSSL/TLSAccess ControlLoggingPerformanceCommon Patterns
Service Management
| Command | Description |
|---|---|
sudo systemctl start apache2 | Start Apache (Debian/Ubuntu) |
sudo systemctl stop apache2 | Stop Apache |
sudo systemctl restart apache2 | Restart Apache (drops connections) |
sudo systemctl reload apache2 | Graceful reload (no dropped connections) |
sudo systemctl enable apache2 | Enable Apache to start on boot |
sudo systemctl status apache2 | Check Apache service status |
apachectl configtest | Test configuration for syntax errors |
apachectl -V | Show Apache version and compile settings |
Configuration Files
| Command | Description |
|---|---|
/etc/apache2/apache2.conf | Main configuration file (Debian/Ubuntu) |
/etc/httpd/conf/httpd.conf | Main configuration file (RHEL/CentOS) |
/etc/apache2/sites-available/ | Virtual host config files (available) |
/etc/apache2/sites-enabled/ | Symlinks to active virtual hosts |
/etc/apache2/mods-available/ | Available module configs |
/etc/apache2/mods-enabled/ | Symlinks to enabled modules |
/etc/apache2/ports.conf | Port listening configuration |
.htaccess | Per-directory config file (requires AllowOverride) |
Virtual Hosts
| Command | Description |
|---|---|
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/example
</VirtualHost> | Basic virtual host configuration |
ServerAlias www.example.com | Add alternate domain names for the virtual host |
ServerAdmin admin@example.com | Set admin email for error pages |
<Directory /var/www/example>
AllowOverride All
Require all granted
</Directory> | Set directory permissions and allow .htaccess |
sudo a2ensite example.conf | Enable a virtual host |
sudo a2dissite example.conf | Disable a virtual host |
ProxyPass / http://localhost:3000/
ProxyPassReverse / http://localhost:3000/ | Reverse proxy to a backend application |
<VirtualHost *:80>
ServerName example.com
Redirect permanent / https://example.com/
</VirtualHost> | Redirect all HTTP traffic to HTTPS |
Modules
| Command | Description |
|---|---|
sudo a2enmod rewrite | Enable a module (e.g., mod_rewrite) |
sudo a2dismod status | Disable a module |
sudo a2enmod ssl | Enable SSL/TLS module |
sudo a2enmod proxy proxy_http | Enable reverse proxy modules |
sudo a2enmod headers | Enable mod_headers for custom HTTP headers |
sudo a2enmod deflate | Enable gzip compression module |
apachectl -M | List all loaded modules |
sudo a2enmod expires | Enable mod_expires for cache control headers |
Rewrite Rules
| Command | Description |
|---|---|
RewriteEngine On | Enable the rewrite engine (required first) |
RewriteRule ^old-page$ /new-page [R=301,L] | Permanent redirect from old URL to new |
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] | Force HTTPS redirect |
RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L] | Remove www prefix from URLs |
RewriteRule ^api/(.*)$ /index.php?route=$1 [QSA,L] | Route API requests to a front controller |
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ /index.html [L] | SPA fallback: serve index.html for non-existing files (React/Vue) |
[L] | Flag: last rule (stop processing) |
[R=301,L] | Flag: permanent redirect and stop |
SSL/TLS
| Command | Description |
|---|---|
sudo a2enmod ssl | Enable the SSL module |
SSLEngine on
SSLCertificateFile /etc/ssl/certs/cert.pem
SSLCertificateKeyFile /etc/ssl/private/key.pem | Basic SSL configuration in VirtualHost :443 |
SSLCertificateChainFile /etc/ssl/certs/chain.pem | Specify the certificate chain file |
sudo certbot --apache -d example.com | Obtain and install Let's Encrypt certificate |
sudo certbot renew --dry-run | Test certificate auto-renewal |
SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1 | Disable old SSL/TLS versions (allow TLS 1.2+ only) |
Header always set Strict-Transport-Security "max-age=63072000" | Enable HSTS header |
Access Control
| Command | Description |
|---|---|
Require all granted | Allow access from all sources |
Require all denied | Deny access from all sources |
Require ip 192.168.1.0/24 | Allow access from specific IP range only |
<Files .env>
Require all denied
</Files> | Block access to specific files |
<FilesMatch "\.(htaccess|htpasswd|ini|log|sh)$">
Require all denied
</FilesMatch> | Block access to sensitive file extensions |
AuthType Basic
AuthName "Restricted"
AuthUserFile /etc/apache2/.htpasswd
Require valid-user | Enable HTTP basic authentication |
sudo htpasswd -c /etc/apache2/.htpasswd username | Create htpasswd file with a user (-c creates new file) |
Logging
| Command | Description |
|---|---|
ErrorLog /var/log/apache2/error.log | Set error log file path |
CustomLog /var/log/apache2/access.log combined | Set access log with combined format |
LogLevel warn | Set log level (emerg, alert, crit, error, warn, notice, info, debug) |
LogFormat "%h %l %u %t \"%r\" %>s %b" common | Define a custom log format |
ErrorLog "|/usr/bin/rotatelogs /var/log/apache2/error.%Y%m%d.log 86400" | Rotate error logs daily using rotatelogs |
sudo tail -f /var/log/apache2/error.log | Follow error log in real time |
CustomLog /var/log/apache2/access.log combined env=!dontlog
SetEnvIf Request_URI "^/health$" dontlog | Exclude health check endpoints from access log |
Performance
| Command | Description |
|---|---|
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule> | Enable gzip compression for text-based content |
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
</IfModule> | Set browser cache expiry by content type |
KeepAlive On
KeepAliveTimeout 5
MaxKeepAliveRequests 100 | Enable keep-alive connections |
<IfModule mod_headers.c>
Header set Cache-Control "public, max-age=31536000"
</IfModule> | Set Cache-Control headers for static assets |
Header set X-Content-Type-Options nosniff
Header set X-Frame-Options SAMEORIGIN
Header set X-XSS-Protection "1; mode=block" | Add security headers |
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150
</IfModule> | Tune MPM prefork for performance |
FileETag None | Disable ETags (useful behind load balancers) |
Common Patterns
| Command | Description |
|---|---|
Options -Indexes | Disable directory listing |
DirectoryIndex index.html index.php | Set default directory index files |
ErrorDocument 404 /404.html | Custom error page |
Header set Access-Control-Allow-Origin "*" | Enable CORS for all origins |
Header always set Access-Control-Allow-Methods "GET, POST, OPTIONS"
Header always set Access-Control-Allow-Headers "Content-Type, Authorization" | Configure CORS methods and headers |
Alias /static /var/www/static
<Directory /var/www/static>
Require all granted
</Directory> | Create URL alias to a directory |
ProxyPass /api http://localhost:8080/api
ProxyPassReverse /api http://localhost:8080/api | Reverse proxy API requests to a backend |
ServerTokens Prod
ServerSignature Off | Hide Apache version in headers and error pages |
📖 Free, searchable command reference. Bookmark this page for quick access.