The Essential Apache .htaccess Cheat Sheet: 301 Redirects, HTTPS & Security
Quick reference for URL rewriting, enforcing HTTPS, blocking bad bots, disabling hotlinking, and setting security headers.
Table of Contents
Common mod_rewrite Directives
Essential URL manipulation and redirect recipes.
| Rule Goal | Code Snippet | Description |
|---|---|---|
| Force HTTPS | `RewriteCond %{HTTPS} off`\n`RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]` | Permanently redirects all HTTP traffic to secure HTTPS protocol. |
| Remove www Prefix | `RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]`\n`RewriteRule ^(.*)$ https://%1/$1 [R=301,L]` | Redirects www.example.com to canonical apex example.com domain. |
| Remove .html Extension | `RewriteCond %{REQUEST_FILENAME} !-f`\n`RewriteRule ^([^.]+)$ $1.html [NC,L]` | Allows serving /about internally from /about.html transparently. |
Security Headers & Hotlink Protection
Hardening headers and preventing third-party bandwidth theft.
# Prevent Image Hotlinking
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https://(www\.)?docswift\.xyz [NC]
RewriteRule \.(jpg|jpeg|png|gif|webp)$ - [F,NC]
# Essential Security Headers
<IfModule mod_headers.c>
Header set X-XSS-Protection "1; mode=block"
Header set X-Frame-Options "SAMEORIGIN"
Header set X-Content-Type-Options "nosniff"
Header set Referrer-Policy "strict-origin-when-cross-origin"
</IfModule>Interactive Client-Side Tools for this Guide
Test and run these patterns directly inside your browser with zero server uploads:
cURL to Fetch, Axios & Python Code Converter
Paste raw cURL commands from browser DevTools and instantly convert them into clean JavaScript, Python, or Go code snippets.
URL Encoder & Decoder (Percent Encoding)
Easily encode query strings, parameter values, and special symbols for REST APIs, web scrapers, and browser links.
SEO URL & Permalinks Slug Generator
Clean article titles, headlines, and product names into search-engine-friendly URLs. Automatically cleans accents, diacritics, and special characters.
Frequently Asked Questions
What does [NC,L,R=301] mean in Apache rewrite rules?
NC means No Case (case-insensitive); L means Last rule (stop evaluating further rewrite rules); R=301 triggers an HTTP 301 Permanent Redirect.
Does .htaccess impact server performance?
Yes. If AllowOverride All is enabled, Apache scans every parent directory for an .htaccess file on every request. High-traffic servers should move rules to VirtualHost files.