Web Server · Apache · HTTP · SSL · Linux

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.

Software: Apache httpd
Version: 2.4.x
Distro: Ubuntu / Debian
Sections: 8
Official Apache Docs 📄 Configuration Guide

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.

Static & dynamic website hosting
SSL/TLS certificate management
Reverse proxy & load balancing
Access control & URL rewriting
30%+
Web Market Share
1995
First Release
2.4.x
Current Branch
Free
Apache License 2.0

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

/etc/apache2/apache2.conf
Main server configuration file. Sets global directives like ServerRoot, Timeout, KeepAlive, and includes other config files.
/etc/apache2/sites-available/
Directory for virtual host config files (one per site). Files here are NOT active until enabled with a2ensite.
/etc/apache2/sites-enabled/
Symlinks to active virtual host configs from sites-available. Apache reads configs from here at startup.
/etc/apache2/mods-available/ & mods-enabled/
Available and enabled Apache modules. Use a2enmod / a2dismod to manage.
/etc/apache2/conf-available/ & conf-enabled/
Additional configuration snippets. Use a2enconf / a2disconf to manage.
/etc/apache2/ports.conf
Defines which ports Apache listens on (default: 80 for HTTP, 443 for HTTPS).
/var/www/html/
Default web root — place your website files here. Customise with DocumentRoot directive.
/var/log/apache2/access.log & error.log
Access log (all requests) and error log. Essential for debugging and security analysis.
# 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

DirectiveDescriptionExample
ServerNameDomain name for this server/vhostServerName example.com
ServerAliasAdditional hostnames for this vhostServerAlias www.example.com
DocumentRootRoot directory for web filesDocumentRoot /var/www/mysite
DirectoryIndexDefault file to serve for a directoryDirectoryIndex index.html index.php
ListenIP/port to listen onListen 80
ErrorLogPath to error log fileErrorLog /var/log/apache2/error.log
CustomLogPath to access log with formatCustomLog /var/log/apache2/access.log combined
LogLevelLogging verbosity levelLogLevel warn
ErrorDocumentCustom error pageErrorDocument 404 /404.html
ServerTokensAmount of server info in headersServerTokens Prod
ServerSignatureServer info in error pagesServerSignature Off
TimeoutConnection timeout in secondsTimeout 300
KeepAliveAllow persistent connectionsKeepAlive On
MaxKeepAliveRequestsMax requests per connectionMaxKeepAliveRequests 100
OptionsControls directory featuresOptions -Indexes +FollowSymLinks
AllowOverrideWhat .htaccess can overrideAllowOverride 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>

📚 Further Learning