The Ultimate .htaccess Cheat Sheet: Commands, Tricks, and Real-World Uses
The .htaccess file is one of the most powerful—and often misunderstood—tools available to developers and server administrators using Apache web servers. Despite being just a simple text file, it can control how your website behaves in profound ways: from redirecting URLs and securing directories to improving performance and customizing error pages.
This guide is designed as a practical, beginner-friendly yet comprehensive cheat sheet. Instead of just explaining concepts, it shows you exactly what commands you can use and how they work.
What Is a .htaccess File?
.htaccess stands for “hypertext access.” It is a configuration file used by Apache-based web servers that allows you to override server settings on a per-directory basis.
Unlike editing the main server config (httpd.conf), .htaccess gives you control without requiring root/server access—making it especially useful for shared hosting environments.
Where to Place the .htaccess File
- Typically placed in your website’s root directory (
public_htmlorwww) - Affects the directory it is in and all subdirectories
- Must be named exactly:
.htaccess
(no filename, just the extension)
Enable .htaccess (If Not Working)
In Apache’s main config:
AllowOverride All
Core Modules Used in .htaccess
Before diving into commands, know these commonly used modules:
mod_rewrite→ URL rewriting and redirectsmod_headers→ control HTTP headersmod_expires→ cachingmod_auth→ authenticationmod_deflate→ compression
1. URL Redirection Cheat Sheet
Redirect a Page (301 Permanent)
Redirect 301 /old-page.html https://example.com/new-page.html
Redirect Entire Site to HTTPS
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
Redirect Non-WWW to WWW
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
Redirect WWW to Non-WWW
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]
Redirect Entire Domain
Redirect 301 / https://newdomain.com/
2. URL Rewriting Cheat Sheet
Enable Rewrite Engine
RewriteEngine On
Clean URLs (Remove .php Extension)
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [L]
Pretty URLs
RewriteRule ^blog/([0-9]+)/?$ blog.php?id=$1 [L]
Force Trailing Slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*[^/])$ /$1/ [L,R=301]
3. Password Protection (Basic Auth)
Protect a Directory
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /full/path/.htpasswd
Require valid-user
Example .htpasswd Entry
username:$apr1$random$hashedpassword
4. Block Access Cheat Sheet
Block Specific IP
Deny from 192.168.1.1
Allow Only One IP
Order Deny,Allow
Deny from all
Allow from 123.123.123.123
Block Multiple IPs
Deny from 111.111.111.111
Deny from 222.222.222.222
Block a Country (basic example)
SetEnvIf GEOIP_COUNTRY_CODE CN BlockCountry
Deny from env=BlockCountry
5. Hotlink Protection
Prevent others from embedding your images:
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https://(www\.)?example.com/ [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [F]
6. Custom Error Pages
404 Page
ErrorDocument 404 /errors/404.html
403 Page
ErrorDocument 403 /errors/403.html
500 Page
ErrorDocument 500 /errors/500.html
7. Caching and Performance
Enable Browser Caching
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/javascript "access 1 month"
</IfModule>
Disable Caching
<FilesMatch "\.(html|php)$">
Header set Cache-Control "no-store, no-cache, must-revalidate"
</FilesMatch>
8. GZIP Compression
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/css application/javascript
</IfModule>
9. Security Hardening
Disable Directory Browsing
Options -Indexes
Prevent Access to .htaccess
<Files .htaccess>
Order allow,deny
Deny from all
</Files>
Block Access to Sensitive Files
<FilesMatch "(config|db|ini|log)">
Deny from all
</FilesMatch>
Disable Script Execution in Uploads
<Directory "/uploads">
php_flag engine off
</Directory>
10. MIME Types
Add MIME Type
AddType application/json .json
Force Download
AddType application/octet-stream .pdf
11. File Handling
Default File
DirectoryIndex index.php index.html
Force Download of Files
<Files "*.zip">
ForceType application/octet-stream
Header set Content-Disposition attachment
</Files>
12. CORS (Cross-Origin Requests)
Header set Access-Control-Allow-Origin "*"
13. Prevent Spam and Bad Bots
Block User Agents
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} BadBot [NC]
RewriteRule .* - [F,L]
Block Empty User Agents
RewriteCond %{HTTP_USER_AGENT} ^-?$
RewriteRule ^ - [F]
14. Force File Download Dialog
Header set Content-Disposition attachment
15. Redirect Based on Browser
RewriteCond %{HTTP_USER_AGENT} Chrome
RewriteRule ^$ chrome.html [L]
16. Time-Based Redirects
RewriteCond %{TIME_HOUR} ^23$
RewriteRule ^$ night.html [L]
17. Prevent Image Indexing by Google
Header set X-Robots-Tag "noindex, noimageindex"
18. Set PHP Settings
php_value upload_max_filesize 64M
php_value post_max_size 64M
php_value max_execution_time 300
19. Disable ETags
FileETag None
20. Remove File Extensions
RewriteEngine On
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*)$ $1.html [L]
21. Force UTF-8 Encoding
AddDefaultCharset UTF-8
22. Redirect Based on Referrer
RewriteCond %{HTTP_REFERER} example.com
RewriteRule .* - [F]
23. Limit Request Size
LimitRequestBody 102400
24. Protect Against Clickjacking
Header always append X-Frame-Options SAMEORIGIN
25. XSS Protection
Header set X-XSS-Protection "1; mode=block"
26. Content Security Policy
Header set Content-Security-Policy "default-src 'self';"
27. Prevent MIME Sniffing
Header set X-Content-Type-Options "nosniff"
28. Redirect Mobile Users
RewriteCond %{HTTP_USER_AGENT} "iPhone|Android" [NC]
RewriteRule ^$ mobile.html [L]
29. Deny Access by File Type
<FilesMatch "\.(exe|sh|bat)$">
Deny from all
</FilesMatch>
30. Logging and Debugging
Enable Rewrite Logging (older Apache)
RewriteLog "/path/to/rewrite.log"
RewriteLogLevel 3
Best Practices
Keep It Clean
- Only include what you need
- Too many rules can slow your server
Test Carefully
- One wrong rule can break your site
- Always back up your
.htaccess
Use 301 Redirects for SEO
- Preserve ranking and authority
Avoid Overusing .htaccess
- Use main server config when possible (faster)
Common Mistakes
- Missing
RewriteEngine On - Incorrect file paths
- Infinite redirect loops
- Case sensitivity issues
- Forgetting to enable required modules
Final Thoughts
The .htaccess file is like a Swiss Army knife for your web server. It gives you control over routing, security, performance, and behavior—all without touching the main server configuration.
For beginners, it might feel overwhelming at first. But once you start using a few key commands—like redirects, rewrites, and security rules—you’ll quickly see how powerful it is.
For advanced users, mastering .htaccess opens the door to fine-grained control that can significantly improve your website’s speed, security, and SEO performance.

With 23+ years in the Web Hosting Industry, Brian has had the opportunity to design websites for some of the largest companies in the industry. Brian currently holds the position as Co-Founder and Creative Director at WebHosting,coop Internet Cooperative