Apache .htaccess Cheat Sheet

Apache .htaccess reference with redirects, rewrites, security headers, caching, and access control. Copy-ready configuration snippets.

46 entries 11 sections

Redirects

Directive Description Example
Permanent redirect Redirect 301 /old-page https://example.com/new-page
Temporary redirect Redirect 302 /promo https://example.com/sale
Redirect with regex pattern RedirectMatch 301 ^/blog/(.*)$ https://blog.example.com/$1

Rewrite

Directive Description Example
Enable mod_rewrite RewriteEngine On (required first)
Set base URL for rewrites RewriteBase /
URL rewrite rule RewriteRule ^page/(.*)$ /index.php?page=$1 [L,QSA]
Condition for rewrite rule RewriteCond %{HTTPS} off
If file doesn't exist RewriteCond %{REQUEST_FILENAME} !-f RewriteRule . /index.php [L]
Match request host RewriteCond %{HTTP_HOST} ^www\. [NC]
Last rule - stop processing RewriteRule ^(.*)$ /index.php [L]
External redirect with code RewriteRule ^old$ /new [R=301,L]
Append query string RewriteRule ^search/(.*)$ /search.php?q=$1 [QSA,L]
Case-insensitive match RewriteCond %{HTTP_HOST} ^WWW\. [NC]
Proxy (reverse proxy) RewriteRule ^api/(.*)$ http://backend:3000/$1 [P]

HTTPS

Directive Description Example
Redirect all HTTP to HTTPS RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
Redirect non-www to www RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
Redirect www to non-www RewriteCond %{HTTP_HOST} ^www\.(.*) [NC] RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

Security

Directive Description Example
Prevent clickjacking Header always set X-Frame-Options DENY
Prevent MIME sniffing Header set X-Content-Type-Options nosniff
Enable HSTS Header set Strict-Transport-Security "max-age=31536000"
Set CSP Header set Content-Security-Policy "default-src 'self'"
Disable directory listing Options -Indexes (prevents browsing directories)
Hide Apache version ServerSignature Off

Access Control

Directive Description Example
Deny all access (2.4+) <Files ".ht*"> Require all denied </Files>
Allow specific IP Require ip 192.168.1.0/24
Apply rules to matching files <FilesMatch "\.(env|log)$"> Require all denied </FilesMatch>
Enable basic authentication AuthType Basic AuthName "Protected" AuthUserFile /path/.htpasswd Require valid-user
Deny access (legacy 2.2) Order deny,allow Deny from all

Caching

Directive Description Example
Set cache expiry by MIME type ExpiresByType image/jpeg "access plus 1 year"
Default cache expiry ExpiresDefault "access plus 1 month"
Set cache control header Header set Cache-Control "max-age=31536000, public"
Check if module is available <IfModule mod_expires.c> ExpiresActive On </IfModule>

Compression

Directive Description Example
Enable gzip compression AddOutputFilterByType DEFLATE text/html text/css application/javascript
Enable compression globally SetOutputFilter DEFLATE
Disable gzip for old browsers BrowserMatch ^Mozilla/4 gzip-only-text/html

MIME Types

Directive Description Example
Associate MIME type with extension AddType application/font-woff2 .woff2
Set character encoding AddDefaultCharset UTF-8
Set default language DefaultLanguage en

Errors

Directive Description Example
Custom error page ErrorDocument 404 /404.html
Custom error message ErrorDocument 403 "Access Forbidden"

CORS

Directive Description Example
Allow cross-origin requests Header set Access-Control-Allow-Origin "*"
Allowed HTTP methods Header set Access-Control-Allow-Methods "GET, POST, OPTIONS"
Allowed request headers Header set Access-Control-Allow-Headers "Content-Type, Authorization"

PHP

Directive Description Example
Set PHP configuration php_value upload_max_filesize 64M
Toggle PHP flag php_flag display_errors Off
Set PHP handler AddHandler application/x-httpd-php .php

Frequently asked questions

What is an .htaccess file?

.htaccess (hypertext access) is a configuration file for Apache web servers that allows per-directory configuration. It's read on every request from the directory it's in and all subdirectories. Common uses: URL rewrites, redirects, access control, caching, and security headers.

Why aren't my RewriteRules working?

Common causes: 1) mod_rewrite isn't enabled (run 'a2enmod rewrite'), 2) AllowOverride is set to None in Apache config (needs 'AllowOverride All'), 3) RewriteEngine On is missing, 4) RewriteBase is wrong, 5) Rule order issues. Check Apache error log for clues.

Should I use .htaccess or Nginx?

.htaccess is Apache-only and has a performance overhead (re-read per request). If you're choosing a new server, Nginx is generally faster for static files and reverse proxying. However, .htaccess is essential for shared hosting and WordPress sites where you can't modify server config.

How do I redirect HTTP to HTTPS?

Add to .htaccess: RewriteEngine On / RewriteCond %{HTTPS} off / RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]. This permanently redirects all HTTP traffic to HTTPS while preserving the full URL path and query string.

How do I set up a single-page app (SPA)?

For React/Vue/Angular apps: RewriteEngine On / RewriteBase / / RewriteRule ^index\.html$ - [L] / RewriteCond %{REQUEST_FILENAME} !-f / RewriteCond %{REQUEST_FILENAME} !-d / RewriteRule . /index.html [L]. This serves index.html for all routes except existing files.

What's the difference between Redirect and RewriteRule?

Redirect is simpler - it does external redirects only (browser URL changes). RewriteRule is more powerful - it can do internal rewrites (URL stays same), external redirects, proxy requests, and supports regex patterns and conditions. Use Redirect for simple cases, RewriteRule for complex logic.

Go from reference to real skills

Cheat sheets are great for quick lookups. Our in-depth courses take you from the fundamentals to professional-level mastery.

Browse all courses