.htaccess Generator — Apache Redirects, Headers and Caching

Build Apache .htaccess rules for redirects, headers, caching, compression and access control, then edit the placeholders before you upload. 100% client-side — your configuration stays private.

.htaccess Generator

What is a .htaccess file? A .htaccess file is a per-directory configuration file for the Apache HTTP Server. Apache reads it on every request to the folder it sits in and to every folder beneath, then applies its directives before the response is sent — redirects, URL rewrites, response headers, cache lifetimes, compression and access control. It works only on Apache, and only when the main server configuration permits it through AllowOverride.

How to Use the .htaccess Generator

  1. Tick the canonical redirects you need — www to non-www, non-www to www, HTTP to HTTPS and trailing-slash removal each emit a RewriteCond and RewriteRule pair. Pick one direction for www — enabling both creates a redirect loop.
  2. Add any one-to-one URL moves — Each From/To pair produces a Redirect 301 line. Use root-relative paths such as /old-page on the left; the right side can be a path or a full URL. Empty rows are skipped.
  3. Set the directory index and custom headersDirectory Index writes a DirectoryIndex line from your comma-separated list. The Custom Headers box is copied through verbatim, so anything you type there must already be valid Apache syntax.
  4. Toggle the security and performance blocks — CORS, cache control, compression, IP blocking, Basic Auth and hotlink protection each add a labelled block. The compression and caching blocks are wrapped in <IfModule> guards so they are ignored rather than fatal when the module is absent.
  5. Generate and replace every placeholder — The output ships with deliberate stand-ins: yourdomain.com in the hotlink rule, /path/to/.htpasswd in the auth block, and two example IPs in the blocking block. None of them will work until you edit them.
  6. Upload as .htaccess and watch the error logDownload saves the file already named .htaccess; put it in your document root. A single unrecognised directive returns HTTP 500 for the whole directory, so reload one page immediately and check the Apache error log before walking away.

How Apache Reads a .htaccess File

A .htaccess file is a fragment of Apache configuration that lives with your content instead of in the server's main config. That difference explains everything about how it behaves. Because it is part of the document tree, you can change it over FTP on shared hosting where you have no access to httpd.conf, and the change takes effect on the very next request with no restart. Because Apache has no way of knowing whether it changed, the server checks for the file in every directory along the path of every request — which is why the Apache documentation recommends using the main configuration whenever you control it.

Two conditions have to hold before a single directive runs. The main configuration must permit overrides for that directory with an AllowOverride setting that covers the directive class you are using, and the module behind the directive must be loaded. Most shared hosts enable AllowOverride All; many self-managed installs ship with AllowOverride None, in which case the file is read and every directive is refused.

Directives apply to the directory containing the file and to every directory below it, with a nearer file overriding a more distant one. There is no partial failure: if Apache does not recognise a directive, it does not skip the line — it returns 500 Internal Server Error for every request under that directory. That is why the caching and compression blocks are wrapped in <IfModule> guards, which turn a missing module into a silently skipped block instead of a broken site.

What Each Option Generates

Every checkbox maps to a small, labelled block of directives. Knowing which Apache module each one depends on tells you in advance what will fail on a stripped-down host.

OptionDirectives writtenModule required
www / non-www, HTTPS, trailing slashRewriteEngine, RewriteCond, RewriteRule with an [R=301,L] flagmod_rewrite
Custom redirect rowsRedirect 301 /from /tomod_alias
Directory IndexDirectoryIndex with your comma-separated listmod_dir
CORS HeadersHeader set Access-Control-Allow-Origin, -Allow-Methods, -Allow-Headersmod_headers
Cache ControlExpiresActive and ExpiresByType for HTML, CSS, JS, images and WOFF2mod_expires
Gzip / Deflate CompressionAddOutputFilterByType DEFLATE for a list of MIME typesmod_deflate
Block IP Addresses<RequireAll> with Require all granted and Require not ipmod_authz_core (Apache 2.4)
Password ProtectionAuthType Basic, AuthName, AuthUserFile, Require valid-usermod_auth_basic
Hotlink ProtectionRewriteCond on HTTP_REFERER plus a [F] rule for image extensionsmod_rewrite

The Require syntax used by the IP blocking option belongs to Apache 2.4. On the long-obsolete 2.2 line the equivalent is Order allow,deny with Deny from, and pasting 2.4 syntax into a 2.2 server produces the 500 described above. Check with apachectl -v if you are unsure which you are on.

Gzip and Deflate are the same filter

The two compression checkboxes look like alternatives but are not. Both emit AddOutputFilterByType DEFLATE, which is mod_deflate's output filter, and despite the name that filter sends Content-Encoding: gzip. The only difference between the two blocks is the MIME list: the first covers HTML, CSS, JavaScript, JSON, SVG and WOFF2; the second adds plain text, XML and RSS. Ticking both simply gives you the union, and there is no conflict in doing so. Note also that WOFF2 and most image formats are already compressed, so listing them costs CPU for close to nothing.

Placeholders and Limits to Fix Before Uploading

The generated file is a template. Several blocks contain stand-in values that are there to show the shape of the directive, and one rule carries an assumption about your domain that will not hold for most sites.

WhereWhat is writtenWhat to do
www to non-wwwThe pattern matches ^www\.(.+)\.com and redirects to %1.comIt only handles .com. For any other suffix, replace .com in both the condition and the target, or match on %{HTTP_HOST} generically
Hotlink protectionyourdomain.com in the referrer conditionSubstitute your real hostname, or every request from your own pages is blocked too
Password protectionAuthUserFile /path/to/.htpasswdUse the absolute server path to a file you created with the htpasswd utility, stored outside the web root
Block IP addressesRequire not ip 123.456.789 and 192.168.1.100Replace both. The first is not even a valid address — 456 exceeds the 0–255 range of an IPv4 octet — and it will be rejected
CORS headersAccess-Control-Allow-Origin "*"Narrow it to the origins that actually need it, and scope it to an API directory rather than the whole site

A wildcard Access-Control-Allow-Origin on your document root lets any website read every response your server produces. It is also incompatible with credentialed requests — browsers reject * when the request carries cookies. Apply CORS to the specific path that serves your API, with the specific origins you intend to allow, and verify the result with the CORS Checker.

Redirect and RewriteRule behave differently

The custom rows use Redirect from mod_alias, while the canonical redirects use RewriteRule from mod_rewrite. Two consequences follow. First, Redirect matches on a path prefix, not an exact path: Redirect 301 /old /new also catches /older and /old/deep/page, forwarding them to /newer and /new/deep/page. If you want exactly one URL moved, use RedirectMatch 301 ^/old$ /new instead. Second, when both modules are active mod_rewrite runs first, so a rewrite that matches will win over a Redirect covering the same path — worth remembering when a redirect you added appears to do nothing.

Frequently Asked Questions

In the document root of your site — the same folder as your home page, often called public_html, htdocs or www. Rules there apply to the whole site. You can also drop a separate file in a subdirectory to apply rules only to that branch; the nearest file wins where two of them set the same directive. The name starts with a dot, so most FTP clients and file managers hide it until you turn on "show hidden files".

No. .htaccess is an Apache feature and no other server reads it. Nginx has no per-directory config file at all — the equivalent rules go in a server or location block and need a reload. Caddy uses a Caddyfile, and IIS uses web.config. Only the intent transfers; the syntax has to be rewritten by hand for each.

Almost always AllowOverride. If the main configuration sets AllowOverride None for your document root, Apache reads the file and refuses every directive in it without an error. Ask your host, or check the <Directory> block in httpd.conf. Other causes: the file is named htaccess.txt because an editor added an extension, it was uploaded to the wrong directory, or a nearer .htaccess further down the tree is overriding it.

An unrecognised directive in .htaccess is fatal for the whole directory, not skipped. The usual culprits are a directive whose module is not loaded, Apache 2.4 Require syntax on a 2.2 server, or a typo in a pasted custom header. The Apache error log names the file and the line number, which turns a ten-minute guess into a ten-second fix. Rename the file to disable it while you investigate.

Not as generated. The rule matches ^www\.(.+)\.com and rebuilds the target as %1.com, so it is hard-coded for .com. On any other suffix it simply never matches and no redirect happens. Edit both the condition and the substitution to your actual suffix, or replace the pair with a rule that strips the leading www. from %{HTTP_HOST} without assuming the ending.

It refuses image requests whose Referer header points at someone else's site, so other people cannot embed your images and spend your bandwidth. It is easy to over-apply. The generated rule allows an empty referrer — which covers direct visits and most privacy-conscious browsers — and your own domain, and blocks everything else with a 403. Remember to replace yourdomain.com, and expect legitimate breakage in feed readers, email clients and search-engine image results.

It writes the directives, but not the credentials. AuthUserFile must point at a real htpasswd file, which you create on the server with the htpasswd command — the format is a username and a hashed password per line, and it should live outside the web root so it cannot be downloaded. Basic Auth sends the password in an easily reversed encoding on every request, so only use it over HTTPS, and treat it as a way to keep a staging site out of view rather than as real access control.

No. The rules are assembled in JavaScript in your tab and nothing is transmitted. One detail worth knowing: pressing Generate writes your checkbox selections into the page URL so a configuration can be bookmarked or shared. The redirect pairs, directory index and custom headers boxes are not written to the URL, so nothing you typed appears in a link you copy.

Use Cases

Mapping URLs After a Site Redesign

Turn a spreadsheet of old and new paths into a block of 301 redirects so external links and search rankings survive the move, and readers with year-old bookmarks land on the replacement page instead of a 404.

Forcing HTTPS on Shared Hosting

Add the HTTP-to-HTTPS rule on a host where you cannot touch the virtual host config, so a certificate you just installed is actually used and mixed-content warnings stop appearing on old inbound links.

Fixing a Slow Static Site

Switch on compression for HTML, CSS and JavaScript and set year-long expiry on images and fonts, which is usually the cheapest available improvement to a page-speed score on a site with no build pipeline.

Choosing One Canonical Hostname

Settle on www or bare domain and redirect the other permanently, so analytics, cookies and search-engine indexing all agree on a single address instead of splitting traffic across two versions of every page.

Hiding a Staging Directory

Put Basic Auth in front of a preview build so clients can review it while search engines and casual visitors cannot, using an htpasswd file you generate on the server and store outside the web root.

Stopping Image Hotlinking

Cut off another site that is embedding your product photos and billing your bandwidth for it, by refusing image requests whose referrer is neither empty nor your own hostname.