.htaccess Generator
Generate Apache .htaccess snippets: force HTTPS, redirect www, expire cache, GZIP compress, block IPs.
What is .htaccess?
.htaccess is an Apache config file. It changes how the server behaves on a per-directory basis, which makes it handy for redirects, security tweaks and cache rules.
The snippets built here can be combined however you like. Just drop the result into your app root. Keep in mind this only takes effect on Apache with mod_rewrite turned on.
Everything is generated right in your browser, nothing leaves your machine.
What is the .htaccess file?
The .htaccess (hypertext access) file is a distributed configuration file used by the Apache HTTP Server. It allows you to apply directives on a per-directory basis without editing the main httpd.conf or restarting the server. Each .htaccess applies to the directory where it lives and to every subdirectory below it, with rules cascading and being overridable at deeper levels.
The syntax is identical to the main configuration file: one directive per line, with optional sections like <IfModule> and <FilesMatch>. The most common modules invoked from .htaccess are mod_rewrite (URL rewriting), mod_headers (response headers), mod_expires (cache control), mod_deflate (gzip compression) and mod_auth_basic (HTTP authentication).
For .htaccess to be honored at all, the server administrator must set AllowOverride to a value other than None in the relevant <Directory> block. The default in modern Apache is None, which silently ignores any directive you place in the file.
When to use (and when NOT to use) .htaccess
Apache itself recommends against .htaccess whenever you can edit the main configuration instead. The reason is performance: when AllowOverride is enabled, Apache walks every parent directory of the requested file on every request, looking for .htaccess files. A request for /www/htdocs/example/file.html triggers four filesystem checks even if no file exists. Rules in .htaccess are also re-read and re-compiled per request, whereas directives in httpd.conf are parsed once at startup.
Use .htaccess when you do not have root access to the server (typical shared hosting, cPanel, Plesk), when a CMS such as WordPress, Joomla or Magento ships its own .htaccess, or when you need fast, frequent tweaks that should not require an Apache reload. Avoid it on high-traffic sites where you control the box: put the same rules inside a <Directory> block in the main config and set AllowOverride None. NGINX has no equivalent and forces this style by design, which is part of why it serves static content noticeably faster than a typical Apache + .htaccess stack.
Most useful directives
RewriteEngine Onactivatesmod_rewrite. Without it, no rewrite rule fires.RewriteRule pattern substitution [flags]defines the URL transformation. Common flags:[R=301]permanent redirect,[L]last rule,[NC]case-insensitive,[QSA]append query string,[F]forbidden (403).RewriteCond TestString Patternguards a rule. Multiple conditions are ANDed; use[OR]for OR.Redirect 301 /old /newandRedirectMatch 301 ^/old-(.*)$ /new-$1frommod_alias— simpler than rewrite for fixed paths.Header set X-Frame-Options "SAMEORIGIN"and similar add response headers.ExpiresActive On+ExpiresByType image/png "access plus 1 year"set browser cache lifetime per MIME type.AddType/AddHandlermap extensions to MIME types or handlers.AuthType Basic,AuthUserFileandRequire valid-userimplement HTTP Basic auth.
Common use cases with examples
Force HTTPS — every HTTP request gets a 301 to the equivalent HTTPS URL, which is a baseline SEO and security recommendation:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Canonicalize www to non-www (or the other way) to consolidate signals for search engines:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
Remove .html / pretty URLs — serve /about from about.html and 301 the legacy form:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^([^.]+)$ $1.html [L]
RewriteCond %{THE_REQUEST} \s/+([^\s]+)\.html [NC]
RewriteRule ^ /%1 [R=301,L]
Security hardening
Block hotlinking of images, deny obvious bots, hide sensitive files and add defensive headers:
# Block access to dotfiles and .htaccess itself
<FilesMatch "^\.|\.(env|git|sql|bak|log)$">
Require all denied
</FilesMatch>
# Disable directory listing
Options -Indexes
# Anti-hotlinking
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?example\.com [NC]
RewriteRule \.(jpe?g|png|gif|webp)$ - [F,NC]
# Block a specific IP
<RequireAll>
Require all granted
Require not ip 203.0.113.5
</RequireAll>
# Defensive headers
Header set X-Frame-Options "SAMEORIGIN"
Header set X-Content-Type-Options "nosniff"
Header set Referrer-Policy "strict-origin-when-cross-origin"
Performance: gzip and cache
Compress text responses and tell browsers to cache static assets aggressively. These two blocks alone usually move a Lighthouse score by 10–30 points:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css text/plain
AddOutputFilterByType DEFLATE application/javascript application/json
AddOutputFilterByType DEFLATE image/svg+xml font/woff2
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/javascript "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/webp "access plus 1 year"
ExpiresByType text/html "access plus 1 hour"
</IfModule>
Common errors
- 500 Internal Server Error after editing — typically a syntax error or a directive not allowed by
AllowOverride. Inspecterror_log. - Rewrite rules ignored —
mod_rewritenot enabled (a2enmod rewrite) orAllowOverride None. - Infinite redirect loop — missing condition that excludes the already-rewritten URL (e.g. forgetting
%{HTTPS} off). - RewriteBase confusion in subdirectory installs — set
RewriteBase /subdir/explicitly. - Header / Expires not applied — module not loaded; wrap blocks in
<IfModule>to fail gracefully.
Generate .htaccess rules for Apache
The .htaccess file commands Apache server behaviour, but its syntax, built on mod_rewrite and specific directives, has a reputation for being hard. This generator assembles the most useful snippets for you, without demanding that you memorise those rules.
It handles frequent tasks: forcing HTTPS, redirecting with or without www, configuring browser cache expiry and enabling GZIP compression. Choose what you need and the tool hands you the block ready to paste into the .htaccess, making the site faster and more secure.
Generation runs in the browser itself. Anyone hosting sites on Apache who wants to apply best practices but gets lost in mod_rewrite syntax will find quite a shortcut here.
Frequently asked questions
Does .htaccess work on NGINX?
Where should I put the file?
301 or 302?
Does it slow down my site?
Is the generated file safe to upload directly?
Related Tools
.htpasswd bcrypt Generator
Build the .htpasswd line with a real bcrypt hash ($2y$ prefix), the scheme Apache recommends. You pick the cost and everything is computed in your browser.
Caddyfile Generator
Generate Caddyfile with automatic HTTPS (Let's Encrypt), reverse_proxy or file_server. Modern simple Caddy 2 syntax.
.htpasswd Generator
Generate .htpasswd lines for Apache/Nginx basic auth. Supports MD5 (apr1), SHA1 and bcrypt hashes. Paste the result straight into the file. Everything in your browser.
Accept-Language Header Parser and q Sorter
Sorts the browser language tags by their q factor, keeps ties in the order sent, and flags q=0 refusals, invalid q values and the * wildcard range.
OpenTelemetry Span JSON Generator
Produce an OpenTelemetry span as JSON with a 32-hex traceId and a 16-hex spanId from the crypto random source, or keep a valid traceId you paste in.
HTTP Accept Header Content Negotiation Matcher
Paste a client Accept header and the comma-separated media types a server offers to see which one wins and at what q value. Exact types and */* only.