Skip to main content

Apache Cheatsheet - HTTP Server Config, VirtualHost, .htaccess, Rewrite, SSL, Proxy

Apache HTTP Server cheatsheet for httpd.conf, VirtualHost, .htaccess, mod_rewrite, SSL, proxying, auth, headers, and logs.

  • Runs locally
  • Category Developer & DevOps
  • Best for Formatting, validating, shrinking, or inspecting code-adjacent text.
Section:
88 entries

Paste an Apache config snippet to detect known directives and common risks. Search above works without any pasted input.

CLI (7)
apachectl configtest

Validate Apache configuration syntax before reload. Debian also accepts `apache2ctl configtest`; RHEL usually has `apachectl` or `httpd -t`.

Watch out: Run this before every reload. A broken config can stop a restart cold.

Examples
sudo apachectl configtest
sudo apache2ctl configtest
sudo httpd -t
apachectl graceful

Gracefully reload config while letting existing requests finish.

Watch out: Use restart only when a graceful reload cannot pick up the change.

Examples
sudo apachectl graceful
sudo apache2ctl graceful
systemctl reload apache2|httpd

Systemd reload for Debian `apache2` or RHEL `httpd` service names.

Examples
sudo systemctl reload apache2
sudo systemctl reload httpd
sudo systemctl status apache2
apachectl -M

List loaded static and shared modules. Fast way to confirm mod_rewrite, mod_proxy, mod_ssl, or mod_headers is active.

Examples
apachectl -M | grep rewrite
apache2ctl -M | grep headers
apachectl -S

Dump parsed virtual hosts, ports, names, aliases, and default vhost choice.

Watch out: If the wrong site answers a host, this command usually explains why.

Examples
sudo apachectl -S
sudo apache2ctl -S
a2ensite / a2dissite

Debian helpers that symlink or unlink files in sites-enabled.

Examples
sudo a2ensite example.conf
sudo a2dissite 000-default.conf
sudo systemctl reload apache2
a2enmod / a2dismod

Debian helpers that enable or disable Apache modules.

Examples
sudo a2enmod rewrite headers ssl proxy_http
sudo a2dismod autoindex
Core (7)
ServerRoot "/etc/apache2"

Base directory for relative Apache config paths. Debian and RHEL use different layouts.

Examples
ServerRoot "/etc/apache2"
ServerRoot "/etc/httpd"
Listen 80

Bind Apache to a port or address. Multiple Listen directives can enable IPv4, IPv6, HTTP, and HTTPS.

Watch out: Port already in use errors come from Listen conflicts or another service on the same port.

Examples
Listen 80
Listen 443 https
Listen 127.0.0.1:8080
IncludeOptional conf-enabled/*.conf

Load optional config files or globs without failing when the glob is empty.

Examples
IncludeOptional conf-enabled/*.conf
IncludeOptional sites-enabled/*.conf
LoadModule rewrite_module modules/mod_rewrite.so

Load a shared module. Most package-managed servers hide this behind a2enmod or conf.modules.d.

Examples
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule ssl_module modules/mod_ssl.so
User www-data / Group www-data

Unix user and group used by worker processes.

Watch out: DocumentRoot files must be readable by this user, not just by your deploy user.

Examples
User www-data
Group www-data
User apache
Group apache
ServerTokens Prod

Reduce version disclosure in server headers.

Examples
ServerTokens Prod
ServerSignature Off
KeepAlive On

Reuse TCP connections for multiple requests. Usually keep it on for browser traffic.

Examples
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
VirtualHost (6)
<VirtualHost *:80>

Define a site for a specific address and port. Name-based vhosts use ServerName and ServerAlias inside this block.

Examples
<VirtualHost *:80>
    ServerName example.com
    DocumentRoot /var/www/example
</VirtualHost>
ServerName example.com

Primary hostname for the vhost. Also fixes AH00558 when set globally.

Examples
ServerName example.com
ServerName localhost
ServerAlias www.example.com

Additional hostnames that should route to the same vhost.

Examples
ServerAlias www.example.com
ServerAlias *.example.net
DocumentRoot "/var/www/site"

Filesystem root for static files served by this vhost.

Watch out: DocumentRoot alone is not enough. Add a matching Directory block with access rules.

Examples
DocumentRoot "/var/www/site/public"
DirectoryIndex index.html index.php

Default files Apache tries when a request maps to a directory.

Examples
DirectoryIndex index.html
DirectoryIndex index.php index.html
ErrorDocument 404 /404.html

Custom error page or response for a status code.

Examples
ErrorDocument 404 /404.html
ErrorDocument 503 "Maintenance window"
Directory (7)
<Directory "/var/www/site">

Attach access, options, and override rules to a filesystem directory.

Examples
<Directory "/var/www/site">
    Require all granted
    Options -Indexes +FollowSymLinks
</Directory>
Require all granted

Allow all clients. Common inside a public DocumentRoot Directory block.

Examples
Require all granted
Require all denied

Deny all clients. Useful for private directories and default-deny blocks.

Examples
Require all denied
Options -Indexes +FollowSymLinks

Enable or disable directory features such as listings, symlinks, CGI, and includes.

Watch out: `Options Indexes` exposes directory listings when no index file exists.

Examples
Options -Indexes +FollowSymLinks
Options None
AllowOverride None

Ignore .htaccess files under this directory. Best default for performance and reviewability.

Examples
AllowOverride None
AllowOverride FileInfo AuthConfig

Allow only selected .htaccess override classes.

Watch out: Prefer narrow classes over `AllowOverride All`.

Examples
AllowOverride FileInfo AuthConfig
AllowOverride None
DirectorySlash On

Redirect directory URLs to include a trailing slash so relative links resolve correctly.

Examples
DirectorySlash On
Rewrite (6)
RewriteEngine On

Enable mod_rewrite rules in this scope.

Watch out: RewriteRule lines do nothing when RewriteEngine is off or mod_rewrite is not loaded.

Examples
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.

Condition applied to the next RewriteRule only.

Examples
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L]

Rewrite or redirect a URL path. The pattern matches a path without the leading slash in per-directory and .htaccess context.

Watch out: For redirects, include `[R=301,L]` or `[R=302,L]` so processing stops after the redirect.

Examples
RewriteRule ^old/(.*)$ /new/$1 [R=301,L]
RewriteRule ^index\.php$ - [L]
Redirect 301 /old /new

Simple prefix redirect from mod_alias. Easier than mod_rewrite when no conditions are needed.

Examples
Redirect 301 /old https://example.com/new
Redirect gone /removed
RedirectMatch 301 ^/docs/(.*)$ /manual/$1

Regex redirect from mod_alias.

Examples
RedirectMatch 301 ^/old/(.*)$ https://example.com/new/$1
RewriteBase /app/

Base path for substitutions in per-directory rewrites. Mostly used in .htaccess under a subdirectory.

Examples
RewriteBase /app/
Proxy (6)
ProxyPass / http://127.0.0.1:3000/

Forward matching requests to an upstream server.

Watch out: Trailing slash behavior matters. Pair with ProxyPassReverse for most HTTP apps.

Examples
ProxyPass / http://127.0.0.1:3000/
ProxyPass /api/ http://app:8080/api/
ProxyPassReverse / http://127.0.0.1:3000/

Rewrite upstream Location headers back to the public URL.

Examples
ProxyPassReverse / http://127.0.0.1:3000/
ProxyPreserveHost On

Send the original Host header to the upstream app.

Examples
ProxyPreserveHost On
RequestHeader set X-Forwarded-Proto "https"

Tell the upstream app the original scheme behind TLS termination.

Examples
RequestHeader set X-Forwarded-Proto "https"
RequestHeader set X-Forwarded-Port "443"
ProxyTimeout 60

Timeout for proxied requests.

Watch out: Raising timeout hides slow upstreams. Fix app latency when possible.

Examples
ProxyTimeout 60
BalancerMember http://app1:8080

Member of a mod_proxy_balancer upstream pool.

Examples
<Proxy "balancer://app">
    BalancerMember http://app1:8080
    BalancerMember http://app2:8080
</Proxy>
ProxyPass / balancer://app/
SSL (5)
SSLEngine on

Enable TLS for this vhost.

Examples
SSLEngine on
SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem

Certificate file presented to clients. Let us Encrypt deployments normally use fullchain.pem.

Watch out: Using only the leaf cert can break clients that need the intermediate chain.

Examples
SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem

Private key matching the certificate.

Examples
SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1

Limit protocol versions. Keep TLS 1.2 and 1.3 for modern public sites.

Examples
SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1
SSLUseStapling on

Enable OCSP stapling when mod_ssl and the certificate chain support it.

Examples
SSLUseStapling on
SSLStaplingCache shmcb:/var/run/ocsp(128000)
Auth (6)
AuthType Basic

Use HTTP Basic authentication for a directory or location.

Examples
AuthType Basic
AuthName "Restricted"

Realm label shown in the browser login prompt.

Examples
AuthName "Restricted area"
AuthUserFile /etc/apache2/.htpasswd

Path to the password file generated by htpasswd.

Watch out: Keep the file outside DocumentRoot so users cannot download hashes.

Examples
AuthUserFile /etc/apache2/.htpasswd
Require valid-user

Allow any authenticated user from the AuthUserFile.

Examples
Require valid-user
Require user alice bob

Allow only named authenticated users.

Examples
Require user alice bob
AuthGroupFile /etc/apache2/.htgroups

Group file for `Require group` rules.

Examples
AuthGroupFile /etc/apache2/.htgroups
Require group admins
Headers (6)
Header set Cache-Control "public, max-age=31536000"

Set a response header using mod_headers.

Examples
Header set Cache-Control "public, max-age=31536000"
Header set X-Content-Type-Options "nosniff"
Header always set Strict-Transport-Security "max-age=31536000"

Set a header even on error responses and redirects.

Watch out: Use HSTS only after HTTPS works for every host you serve.

Examples
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
RequestHeader set X-Forwarded-Proto "https"

Set a request header before Apache proxies to the upstream.

Examples
RequestHeader set X-Forwarded-Proto "https"
SetEnvIfNoCase User-Agent "bot" is_bot

Set environment variables based on request metadata.

Examples
SetEnvIfNoCase User-Agent "bot" is_bot
CustomLog logs/access.log combined env=!is_bot
AddType application/wasm .wasm

Map file extensions to MIME types.

Examples
AddType application/wasm .wasm
AddType image/svg+xml .svg
AddOutputFilterByType DEFLATE text/html text/css application/javascript

Compress selected response types with mod_deflate.

Examples
AddOutputFilterByType DEFLATE text/html text/plain text/css application/javascript
Cache (6)
ExpiresActive On

Enable mod_expires rules in the current scope.

Examples
ExpiresActive On
ExpiresByType image/png "access plus 1 year"

Set browser cache expiration by MIME type.

Examples
ExpiresByType text/css "access plus 1 month"
ExpiresByType image/png "access plus 1 year"
CacheQuickHandler off

Let normal auth and rewrite phases run before mod_cache serves cached content.

Examples
CacheQuickHandler off
CacheRoot "/var/cache/apache2/mod_cache_disk"

Disk path used by mod_cache_disk.

Examples
CacheRoot "/var/cache/apache2/mod_cache_disk"
CacheEnable disk /

Enable a cache provider for a URL path.

Examples
CacheEnable disk /assets/
CacheDisable /api/
DeflateCompressionLevel 6

Compression level for mod_deflate. Higher is not always better under CPU pressure.

Examples
DeflateCompressionLevel 6
Logs (5)
ErrorLog ${APACHE_LOG_DIR}/error.log

Main error log path. Debug most config and permission issues here first.

Examples
ErrorLog ${APACHE_LOG_DIR}/error.log
ErrorLog /var/log/httpd/example-error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

Access log path plus LogFormat name.

Examples
CustomLog ${APACHE_LOG_DIR}/access.log combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common

Define a named access-log format.

Examples
LogFormat "%h %l %u %t \"%r\" %>s %b" common
LogFormat "%v %h %>s %D \"%r\"" vhost_timing
LogLevel warn

Error log verbosity. Raise temporarily when debugging modules.

Examples
LogLevel warn
LogLevel rewrite:trace3 proxy:debug
CustomLog "|/usr/sbin/rotatelogs /var/log/apache2/access.%Y%m%d 86400" combined

Pipe logs through rotatelogs for time-based rotation.

Examples
CustomLog "|/usr/sbin/rotatelogs /var/log/apache2/access.%Y%m%d 86400" combined
.htaccess (4)
.htaccess

Per-directory config file read at request time when AllowOverride permits it.

Watch out: It is slower and harder to audit than vhost config. Use only when needed.

Examples
# .htaccess
RewriteEngine On
RewriteRule ^old$ /new [R=301,L]
AllowOverride All

Allow every .htaccess override class.

Watch out: Avoid as a default. It expands attack surface and makes behavior depend on files outside vhost review.

Examples
AllowOverride FileInfo AuthConfig
# Avoid broad default:
AllowOverride All
<FilesMatch "\.php$">

Apply rules to files whose names match a regex.

Examples
<FilesMatch "\.inc$">
    Require all denied
</FilesMatch>
AddHandler application/x-httpd-php .php

Map a handler to file extensions. Common on shared hosting, risky when misapplied.

Examples
AddHandler application/x-httpd-php .php
Security (6)
TraceEnable Off

Disable HTTP TRACE.

Examples
TraceEnable Off
ServerSignature Off

Hide server signature on generated error pages.

Examples
ServerSignature Off
Options -Indexes

Disable directory listing.

Examples
Options -Indexes
Require ip 10.0.0.0/8

Allow only selected client IP ranges.

Examples
Require ip 10.0.0.0/8
Require ip 192.168.1.0/24
<LimitExcept GET POST>

Apply authz rules to all methods except the listed ones.

Examples
<LimitExcept GET POST>
    Require all denied
</LimitExcept>
FileETag None

Disable file-based ETags when inode/path leakage or multi-node mismatch matters.

Examples
FileETag None
Troubleshoot (6)
403 Forbidden

Check Directory `Require`, filesystem permissions, SELinux, and .htaccess overrides.

Examples
sudo tail -f /var/log/apache2/error.log
namei -l /var/www/site/index.html
404 Not Found

Check the vhost selected by apachectl -S, DocumentRoot, Alias, and rewrite target.

Examples
sudo apachectl -S
curl -I http://example.com/path
500 Internal Server Error

Often a .htaccess syntax error, CGI/PHP handler issue, or module directive not allowed in that context.

Examples
tail -f /var/log/apache2/error.log
apachectl configtest
502 Proxy Error

Apache reached proxy handling but the upstream refused, closed, or timed out.

Examples
curl -v http://127.0.0.1:3000/
LogLevel proxy:debug
AH00558 could not reliably determine the server name

Set a global ServerName to silence the startup warning.

Examples
ServerName localhost
echo "ServerName localhost" | sudo tee /etc/apache2/conf-available/servername.conf
AH00072 make_sock could not bind

Port is already bound or Listen directives conflict.

Examples
sudo ss -ltnp | grep ":80"
sudo apachectl -S
Templates (5)
Static site vhost

Minimal HTTP vhost for static files.

Examples
<VirtualHost *:80>
    ServerName example.com
    DocumentRoot /var/www/example/public
    <Directory "/var/www/example/public">
        Require all granted
        Options -Indexes +FollowSymLinks
        AllowOverride None
    </Directory>
</VirtualHost>
HTTPS vhost

TLS vhost using Let us Encrypt paths.

Examples
<VirtualHost *:443>
    ServerName example.com
    DocumentRoot /var/www/example/public
    SSLEngine on
    SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
</VirtualHost>
Reverse proxy vhost

Apache fronting a local app server.

Examples
<VirtualHost *:80>
    ServerName app.example.com
    ProxyPreserveHost On
    ProxyPass / http://127.0.0.1:3000/
    ProxyPassReverse / http://127.0.0.1:3000/
</VirtualHost>
.htaccess HTTPS redirect

Canonical HTTPS redirect for shared hosting .htaccess.

Examples
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Basic auth directory

Protect a directory with htpasswd users.

Examples
<Directory "/var/www/private">
    AuthType Basic
    AuthName "Restricted"
    AuthUserFile /etc/apache2/.htpasswd
    Require valid-user
</Directory>

What this tool does

Searchable Apache HTTP Server cheatsheet for the config work admins actually do: apachectl configtest, graceful reloads, VirtualHost blocks, ServerName, DocumentRoot, Directory permissions, AllowOverride, Options, Require, mod_rewrite redirects, .htaccess rules, ProxyPass / ProxyPassReverse, SSL certificates, headers, caching, compression, auth, log formats, and common 403 / 404 / 500 / 502 debugging paths. The tool is fully local: search the reference, filter by section, paste a small config snippet to detect known directives and likely mistakes, then copy the exact directive or example you need. It is written for day-to-day Apache/httpd operations, especially when you are moving between Debian apache2 paths, RHEL httpd paths, shared-host .htaccess files, and reverse-proxy vhosts.

Tool details

Input
Files + Text
The page exposes text boxes, numeric controls, file pickers, or structured inputs depending on the tool.
Output
Live result + Copy + Preview
The result area focuses on usable output, with copy, download, or preview actions when supported.
Privacy
Browser-side processing
The main tool logic does not call an external API, so inputs normally stay in the current tab.
Save / share
Shareable URL state
Key settings are encoded in the URL so another person can reopen the same setup.
Performance budget
Initial JS <= 34 KB
No WASM budget is declared, keeping the tool quick to open on mobile.
Best fit
Developer & DevOps · Developer
Category and role tags drive related tools, internal links, and quick fit checks.

How to use

  1. 1. Input

    Paste or drop your content into the tool panel.

  2. 2. Process

    Click the button. All processing is local in your browser.

  3. 3. Copy / Download

    Copy the result or download to disk in one click.

How Apache Cheatsheet fits into your work

Use it in the small gaps between coding, reviewing, debugging, and shipping.

Developer jobs

  • Formatting, validating, shrinking, or inspecting code-adjacent text.
  • Preparing snippets for documentation, tickets, commits, or handoff.
  • Checking a small payload quickly without switching tools.

Developer checks

  • Run irreversible transforms like minify or obfuscate on a copy.
  • Keep secrets out of pasted snippets unless the tool explicitly stays local.
  • Use your normal tests or linter before shipping transformed code.

Good next steps

These links move the current task into a more complete workflow.

  1. 1 Nginx Cheatsheet Nginx cheat sheet — common configs, location/server blocks, SSL, reverse proxy, gzip, real examples & gotchas. Open
  2. 2 .htaccess Generator Generate Apache .htaccess — HTTPS redirect, www toggle, gzip, cache headers, hotlink protection. Open
  3. 3 .htpasswd Generator Generate Apache/Nginx .htpasswd lines — bcrypt, apr1 (MD5), SHA-1 — multi-user, copy, download — 100% browser-only Open

Real-world use cases

  • Fix a 403 after moving a site to a new DocumentRoot

    You paste the vhost and Directory block, see the tool detect DocumentRoot, Directory, Require, and Options, then jump to the 403 and Directory entries. The checklist points you to `Require all granted`, file permissions for the Apache user, and the exact error-log line to tail.

  • Convert an app server into an Apache reverse-proxy vhost

    Search for ProxyPass and copy the paired ProxyPassReverse example. The analyzer warns when a snippet has ProxyPass without the reverse mapping, which is the common cause of redirects leaking the upstream host or path.

  • Decide whether a rewrite belongs in .htaccess

    When a shared-hosting support ticket asks for a rewrite, filter to Rewrite and .htaccess. The notes show the difference between Redirect, RewriteRule, RewriteCond, and AllowOverride so you can keep the override narrow instead of enabling every .htaccess feature.

Common pitfalls

  • Enabling `AllowOverride All` everywhere makes every request scan for .htaccess files and lets directory-local rules override reviewed vhost config. Use a narrow override class or move rules into the vhost.

  • Adding `ProxyPass` without `ProxyPassReverse` often makes upstream redirects leak internal hostnames. Treat them as a pair unless you have a specific reason.

  • Using `Options Indexes` on a public directory exposes directory listings when no index file exists. Prefer `Options -Indexes` unless browsing is intentional.

Privacy

Apache configs can include private paths, internal hostnames, and upstream URLs, so the snippet textarea is deliberately local-only and not synced into URL state. Compact search and category filters are shareable; pasted config never leaves the tab.

FAQ

Tool combos

Folks in your role tend to reach for these alongside this tool.

Made by Toolora · 100% client-side · Updated 2026-06-13