Apache Web Server
Cheatsheet
A practical reference for Apache HTTP Server — covering configuration files, key directives, virtual hosts, SSL/TLS setup, .htaccess, and server management commands.
What is Apache HTTP Server?
The Apache HTTP Server (commonly called "Apache") is the world's most widely deployed open-source web server, maintained by the Apache Software Foundation. First released in 1995, it powers over 30% of all active websites globally.
What it does: Apache receives HTTP/HTTPS requests from clients (browsers) and serves web content — static files (HTML, CSS, images) or dynamic content via modules like PHP, Python (mod_wsgi), or reverse proxy to application servers.
Real-world use: Web hosting, LAMP stack (Linux + Apache + MySQL + PHP), reverse proxying to Node.js/Python apps, SSL termination, and serving APIs. It is a core skill for web developers, sysadmins, and DevOps engineers.
1. Install & Service Management
# Install (Ubuntu / Debian) sudo apt update && sudo apt install apache2 # Service management (systemd) sudo systemctl start apache2 # start sudo systemctl stop apache2 # stop sudo systemctl restart apache2 # restart (applies config changes) sudo systemctl reload apache2 # graceful reload (no downtime) sudo systemctl enable apache2 # start on boot sudo systemctl disable apache2 # don't start on boot sudo systemctl status apache2 # check status # Legacy service command sudo service apache2 restart # Test configuration before reloading sudo apache2ctl configtest # check for syntax errors sudo apache2ctl -t # same as configtest sudo apache2ctl -M # list loaded modules sudo apache2ctl -S # show virtual host settings
2. Key Configuration Files & Directories
# Enable / disable sites and modules sudo a2ensite mysite.conf # enable virtual host sudo a2dissite mysite.conf # disable virtual host sudo a2enmod rewrite # enable mod_rewrite sudo a2dismod status # disable mod_status sudo a2enmod ssl # enable SSL module sudo a2enmod headers # enable headers module sudo systemctl reload apache2 # apply changes
3. Key Configuration Directives
| Directive | Description | Example |
|---|---|---|
| ServerName | Domain name for this server/vhost | ServerName example.com |
| ServerAlias | Additional hostnames for this vhost | ServerAlias www.example.com |
| DocumentRoot | Root directory for web files | DocumentRoot /var/www/mysite |
| DirectoryIndex | Default file to serve for a directory | DirectoryIndex index.html index.php |
| Listen | IP/port to listen on | Listen 80 |
| ErrorLog | Path to error log file | ErrorLog /var/log/apache2/error.log |
| CustomLog | Path to access log with format | CustomLog /var/log/apache2/access.log combined |
| LogLevel | Logging verbosity level | LogLevel warn |
| ErrorDocument | Custom error page | ErrorDocument 404 /404.html |
| ServerTokens | Amount of server info in headers | ServerTokens Prod |
| ServerSignature | Server info in error pages | ServerSignature Off |
| Timeout | Connection timeout in seconds | Timeout 300 |
| KeepAlive | Allow persistent connections | KeepAlive On |
| MaxKeepAliveRequests | Max requests per connection | MaxKeepAliveRequests 100 |
| Options | Controls directory features | Options -Indexes +FollowSymLinks |
| AllowOverride | What .htaccess can override | AllowOverride All |
4. Virtual Hosts
Virtual hosts allow one Apache server to serve multiple websites on the same IP address.
HTTP Virtual Host
# /etc/apache2/sites-available/example.com.conf
<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/example.com
ErrorLog ${APACHE_LOG_DIR}/example-error.log
CustomLog ${APACHE_LOG_DIR}/example-access.log combined
<Directory /var/www/example.com>
Options -Indexes +FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
HTTPS Virtual Host
<VirtualHost *:443>
ServerName example.com
DocumentRoot /var/www/example.com
SSLEngine on
SSLCertificateFile /etc/ssl/certs/cert.pem
SSLCertificateKeyFile /etc/ssl/private/key.pem
SSLCertificateChainFile /etc/ssl/certs/chain.pem
Header always set Strict-Transport-Security \
"max-age=63072000; includeSubDomains"
</VirtualHost>
# HTTP → HTTPS redirect (in port 80 vhost) <VirtualHost *:80> ServerName example.com Redirect permanent / https://example.com/ </VirtualHost> # OR with mod_rewrite (more flexible) RewriteEngine On RewriteCond %{HTTPS} off RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
5. .htaccess Common Patterns
The .htaccess file provides per-directory configuration. Requires AllowOverride All in server config.
# Enable mod_rewrite Options +FollowSymLinks RewriteEngine On # Remove .html extension from URLs RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.html -f RewriteRule ^(.+)$ $1.html [L,QSA] # Redirect old URL to new URL Redirect 301 /old-page.html /new-page.html # Block access to specific files <Files "config.php"> Require all denied </Files> # Block access to .env files <FilesMatch "^\.env"> Require all denied </FilesMatch> # Protect directory with password AuthType Basic AuthName "Restricted Area" AuthUserFile /etc/.htpasswd Require valid-user # Custom error pages ErrorDocument 404 /errors/404.html ErrorDocument 500 /errors/500.html # Enable GZIP compression <IfModule mod_deflate.c> AddOutputFilterByType DEFLATE text/html text/css application/javascript </IfModule> # Set browser caching headers <FilesMatch "\.(jpg|png|css|js)$"> Header set Cache-Control "max-age=2592000, public" </FilesMatch>
6. SSL / Let's Encrypt (Certbot)
# Install certbot for Apache sudo apt install certbot python3-certbot-apache # Obtain and install certificate automatically sudo certbot --apache -d example.com -d www.example.com # Certificate only (no Apache config change) sudo certbot certonly --apache -d example.com # Renew all certificates sudo certbot renew # Test renewal (dry run) sudo certbot renew --dry-run # Cert locations (Let's Encrypt) /etc/letsencrypt/live/example.com/fullchain.pem /etc/letsencrypt/live/example.com/privkey.pem /etc/letsencrypt/live/example.com/chain.pem # Enable SSL module manually sudo a2enmod ssl sudo a2enmod headers sudo systemctl restart apache2
7. Reverse Proxy
Forward incoming requests to a backend application server (Node.js, Python, Java, etc.).
# Enable required modules sudo a2enmod proxy proxy_http proxy_wstunnel # Basic reverse proxy in VirtualHost <VirtualHost *:443> ServerName api.example.com SSLEngine on ... ProxyPreserveHost On ProxyPass / http://localhost:3000/ ProxyPassReverse / http://localhost:3000/ # WebSocket proxy RewriteEngine On RewriteCond %{HTTP:Upgrade} websocket [NC] RewriteRule /(.*) ws://localhost:3000/$1 [P,L] </VirtualHost>
8. Security Hardening
# In apache2.conf — hide version info ServerTokens Prod ServerSignature Off # Disable directory listing globally <Directory /> Options -Indexes </Directory> # Security headers (mod_headers required) 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 Content-Security-Policy "default-src 'self'" Header always set Strict-Transport-Security "max-age=63072000" # Restrict HTTP methods <LimitExcept GET POST HEAD> Require all denied </LimitExcept> # Block access to sensitive files <FilesMatch "\.(htaccess|htpasswd|env|git|bak)$"> Require all denied </FilesMatch> # Rate limiting (mod_ratelimit) <Location /> SetOutputFilter RATE_LIMIT SetEnv rate-limit 400 </Location>