DevTools Logo

Apache HTTP Server & .htaccess Cheat Sheet

Quick reference for Apache HTTP Server: virtual hosts, directives, URL rewriting, .htaccess, and security hardening.

Web & Network
apache
htaccess
web-server

Apache HTTP Server is configured through httpd.conf (or apache2.conf) plus per-directory .htaccess files. .htaccess is best for shared hosting and directory scoping; the main config is preferred when you control the server.

Virtual Host

apache
<VirtualHost *:80>
  ServerName example.com
  ServerAlias www.example.com
  DocumentRoot /var/www/example
  ErrorLog  ${APACHE_LOG_DIR}/error.log
  CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

<VirtualHost *:443>
  ServerName example.com
  DocumentRoot /var/www/example
  SSLEngine on
  SSLCertificateFile      /etc/ssl/certs/example.crt
  SSLCertificateKeyFile   /etc/ssl/private/example.key
</VirtualHost>
Table
DirectivePurpose
<VirtualHost>One site/port block
ServerNamePrimary hostname
ServerAliasAdditional hostnames
DocumentRootFilesystem root for the site
Listen 80Port the server binds
DirectoryIndexDefault file (index.html)

Directory & Access Control

apache
<Directory /var/www/example>
  Options -Indexes
  AllowOverride All
  Require all granted
</Directory>

# Block a path
<Directory /var/www/example/private>
  Require ip 192.168.1.0/24
</Directory>

.htaccess: Rewrite & Redirects

Enable the module first: a2enmod rewrite. Then:

apache
RewriteEngine On

# Force HTTPS (except already on HTTPS)
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Pretty URLs: /page/123 → index.php?page=123
RewriteRule ^page/([0-9]+)/?$ index.php?page=$1 [L,QSA]

# Block dotfiles
RewriteRule (^\.|/\.) - [F]
Table
DirectiveMeaning
RewriteCond %{HTTPS} offCondition before the rule
RewriteRule pattern target [flags]Rewrite/replace URL
[L]Last rule — stop processing
[R=301]Redirect (301 permanent)
[QSA]Append the original query string
[F]Forbidden (403)
[NC]Case-insensitive match
$1, $2Backreferences from capture groups

Security Header Hardening

apache
<IfModule mod_headers.c>
  Header always set X-Content-Type-Options "nosniff"
  Header always set X-Frame-Options "SAMEORIGIN"
  Header always set Referrer-Policy "strict-origin-when-cross-origin"
  Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
  Header always set Content-Security-Policy "default-src 'self'"
</IfModule>

Common Pitfalls

[!WARNING] Options -Indexes prevents directory listing, but never rely on it for security — sensitive files must still be denied by Require rules or moved outside DocumentRoot.

[!TIP] Prefer Redirect 301 /old /new in .htaccess for simple path moves and reserve mod_rewrite for pattern-based rewriting — Redirect is clearer and cheaper.

References