HTACCESS Directives & Rewrite Rules Generator
Generate production-ready Apache .htaccess rules with 301 redirects, HTTPS enforcement, GZIP, and security headers.
Configuration Options
Quick Production Profiles
Generated .htaccess Output
Apache Directives# ==============================================================================
# APACHE .HTACCESS PRODUCTION DIRECTIVES & REWRITE RULES
# Generated via TwisterTools.com htaccess-generator on 2026-08-20
# ==============================================================================
# ------------------------------------------------------------------------------
# 1. CORE SERVER DEFAULTS & CHARACTER ENCODING
# ------------------------------------------------------------------------------
Options -Indexes
Options +FollowSymLinks
AddDefaultCharset UTF-8
ServerSignature Off
# ------------------------------------------------------------------------------
# 2. CUSTOM ERROR HANDLERS
# ------------------------------------------------------------------------------
ErrorDocument 403 /403.html
ErrorDocument 404 /404.html
ErrorDocument 500 /500.html
# ------------------------------------------------------------------------------
# 3. SECURITY HEADERS & BROWSER HARDENING
# ------------------------------------------------------------------------------
<IfModule mod_headers.c>
Header always set X-Frame-Options "SAMEORIGIN"
Header always set X-Content-Type-Options "nosniff"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
Header always set X-XSS-Protection "1; mode=block"
Header always set Permissions-Policy "geolocation=(), microphone=(), camera=()"
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains" env=HTTPS
Header set X-Frame-Options "SAMEORIGIN"
</IfModule>
# ------------------------------------------------------------------------------
# 4. PROTECT SENSITIVE SYSTEM FILES & DOTFILES
# ------------------------------------------------------------------------------
<FilesMatch "^\.(htaccess|htpasswd|env|git|svn|json|lock|bak|config|sql|log|sh)$">
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Order deny,allow
Deny from all
</IfModule>
</FilesMatch>
# ------------------------------------------------------------------------------
# 6. MOD_DEFLATE / GZIP COMPRESSION
# ------------------------------------------------------------------------------
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css
AddOutputFilterByType DEFLATE application/javascript application/x-javascript
AddOutputFilterByType DEFLATE application/json application/xml application/rss+xml
AddOutputFilterByType DEFLATE image/svg+xml font/ttf font/otf font/woff font/woff2
</IfModule>
# ------------------------------------------------------------------------------
# 7. MOD_EXPIRES BROWSER CACHING (LEVERAGE CACHE)
# ------------------------------------------------------------------------------
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 2 days"
# Images & Icons
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/webp "access plus 1 year"
ExpiresByType image/avif "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/svg+xml "access plus 1 year"
ExpiresByType image/x-icon "access plus 1 year"
# CSS, JavaScript & Fonts
ExpiresByType text/css "access plus 1 month"
ExpiresByType text/javascript "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType font/woff2 "access plus 1 year"
ExpiresByType font/woff "access plus 1 year"
# Media & Audio/Video
ExpiresByType video/mp4 "access plus 1 month"
ExpiresByType video/webm "access plus 1 month"
</IfModule>
# ------------------------------------------------------------------------------
# 8. MOD_REWRITE ENGINE DIRECTIVES & CANONICAL RULES
# ------------------------------------------------------------------------------
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
# Block Scrapers & Malicious Spiders
RewriteCond %{HTTP_USER_AGENT} (libwww-perl|wget|python|nikto|curl|scan|clshttp|archiver|loader|email|harvest|extract|grab|miner) [NC]
RewriteRule .* - [F,L]
# Enforce Secure HTTPS Connection
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP:X-Forwarded-Proto} !https [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
# Canonical Force Non-WWW
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
# Clean .php Extension (Hide Extension in URLs)
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]
# Custom Canonical Redirects
RewriteRule ^old-page$ /new-page [R=301,L]
</IfModule>
# ==============================================================================
# END OF APACHE .HTACCESS CONFIGURATION
# ==============================================================================Understanding Apache .htaccess Architecture & Directory Directives
An .htaccess (Hypertext Access) file is an Apache Web Server directory-level configuration file. It empowers site administrators to execute decentralized server configurations, granular URL rewrites, browser cache lifetimes, and robust access controls without requiring direct access to the global server configuration file (httpd.conf).
Execution Precedence & Scope
When a client requests a URL, Apache traverses from the server root down through every subdirectory to evaluate active .htaccess files. Directives in subfolders override inherited rules from parent folders.
Mod_Rewrite Engine Pipeline
The mod_rewrite module executes regular expression matching against incoming server variables (%{HTTP_HOST}, %{REQUEST_URI}) to perform URL canonicalization and redirects seamlessly.
Essential Apache Mod_Rewrite Flags & Status Codes
Apache RewriteRules utilize flags enclosed in square brackets at the end of each directive. Understanding these flags ensures predictable routing behavior:
| Rewrite Flag | Technical Description | Practical Use Case |
|---|---|---|
| [R=301,L] | Permanent HTTP 301 Redirect; halts processing further rules. | Enforcing HTTPS, moving URLs, and canonical domain forwarding. |
| [R=302,L] | Temporary HTTP 302 Redirect; prevents search engines from indexing target permanently. | Maintenance windows, staging redirects, and short-term promotions. |
| [NC] | No Case; performs case-insensitive regex matching. | Matching domain names or varied user agent strings regardless of capitalization. |
| [F,L] | Forbidden (HTTP 403); halts rule execution and denies access. | Blocking scrapers, aggressive spiders, and hotlinking requests. |
| [QSA] | Query String Append; preserves existing URL query parameters during rewrites. | Clean routing where query arguments like `?ref=google` must persist. |
Production Security Hardening & Threat Mitigation
A robust .htaccess acts as a first line of defense before incoming HTTP requests touch application code or databases:
Dotfile & Credential Protection
Denies access to sensitive development artifacts including .env, .git, database dumps, and server backups.
Strict Security Headers
Employs X-Frame-Options: SAMEORIGIN and X-Content-Type-Options: nosniff to prevent clickjacking and MIME-type sniffing attacks.
Bot & Scraper Filtration
Intercepts known scanning tools and scrapers (e.g., Nikto, Wget, automated extractors) before they can consume CPU bandwidth.
Frequently Asked Questions (FAQ)
What is an Apache .htaccess file and where should it be located?
An .htaccess (Hypertext Access) file is a directory-level configuration file supported by the Apache HTTP Server. It allows webmasters to alter server configurations per directory without editing main Apache configuration files (httpd.conf). It is typically placed in the root directory (public_html, htdocs, or www) of your website.
What is the difference between a 301 and 302 redirect in .htaccess?
A 301 redirect indicates a permanent URL movement, passing 90-99% of search engine ranking equity (PageRank) to the new destination. A 302 redirect is a temporary redirect that instructs crawlers to keep indexing the original URL.
Why is forcing HTTPS and HSTS critical for website security?
Enforcing HTTPS encrypts all plaintext communication between client browsers and the Apache server. HTTP Strict Transport Security (HSTS) prevents SSL-stripping man-in-the-middle attacks by forcing browsers to interact with the domain solely over HTTPS.
How does mod_deflate / GZIP compression improve page speed?
The mod_deflate module compresses text-based assets (HTML, CSS, JavaScript, JSON, SVG) on the server before transmitting them across the network, reducing data payload sizes by up to 70% and accelerating page load speeds.
How do mod_expires browser caching directives work?
mod_expires instructs client browsers and CDNs to cache static assets locally for a predetermined period (e.g., 1 year for images, 1 month for CSS/JS). This eliminates redundant server requests on repeat visits.
Why are dotfiles and sensitive configuration files blocked by default?
Sensitive files like .env, .git, .htpasswd, and package.json often store database credentials, API secret keys, and source repositories. Blocking access via FilesMatch prevents unauthorized web visitors from viewing private system credentials.
Related & Complementary Utilities
Explore more privacy-first client-side web tools.
JWT Decoder, Inspector & Payload Auditor
Decode JSON Web Tokens (JWT) locally to inspect header parameters, payload claims, and expiration timestamps without transmitting secret keys over the wire.
Cron Expression Generator & Explainer
Generate and explain cron expressions with real-time human-readable translations, next execution dates, and custom schedulers.
CSS Grid Generator & Interactive Builder
Design responsive 2D layouts visually with fractional tracks, minmax constraints, and instant CSS/Tailwind export.