Web Server & SysadminUpdated: 2026-11-07

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.

The Apache .htaccess file is a directory-level configuration file that allows website operators to configure URL routing, caching, security headers, and access controls without modifying main server configuration files.

Common mod_rewrite Directives

Essential URL manipulation and redirect recipes.

Rule GoalCode SnippetDescription
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.

Hotlink Protection & Headers Blockapache
# 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>

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.