1001Ferramentas
🔧Dev

.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 On activates mod_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 Pattern guards a rule. Multiple conditions are ANDed; use [OR] for OR.
  • Redirect 301 /old /new and RedirectMatch 301 ^/old-(.*)$ /new-$1 from mod_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 / AddHandler map extensions to MIME types or handlers.
  • AuthType Basic, AuthUserFile and Require valid-user implement 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. Inspect error_log.
  • Rewrite rules ignoredmod_rewrite not enabled (a2enmod rewrite) or AllowOverride 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.

FAQ

Does .htaccess work on NGINX? No. NGINX has no per-directory config; you must translate rules into the server or location blocks of nginx.conf.

Where should I put the file? In the document root (e.g. /var/www/html/) for site-wide rules. The filename starts with a dot, so it is hidden on Unix-like systems.

301 or 302? Use [R=301] for permanent moves (search engines transfer ranking signals) and [R=302] only for temporary redirects.

Does it slow down my site? Yes, marginally — every request walks the directory tree to find .htaccess files. The compression and cache rules it enables almost always more than compensate.

Is the generated file safe to upload directly? Test it on a staging copy first, keep a backup of the previous file, and check the Apache error log after deploying.

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.

Related Tools