.htaccess Generator

Build a ready .htaccess file: www redirect, forced HTTPS, blocked .git and .env, custom 404 page, compression. Copy it or download the file.

Everything runs in your browser — your data is never sent to any server.

Why an .htaccess generator is worth using

An .htaccess file is a plain text configuration for Apache that changes how a site behaves without access to the control panel and without touching the main server configuration. Most often it holds a redirect from www to the bare domain, a forced HTTPS rule, the move of old pages and a block on service files such as .git and .env. Writing such a file from scratch carries risk: one stray brace or a module the server does not have brings the whole site down with a 500 error. This generator assembles the file from separate rules, each one shipped with a comment, and shows the result as it will land on the server.

What the .htaccess generator does

  • Redirects from www to the bare domain and back, built around the domain you type in
  • Forced HTTPS and a page move with a choice of the 301 or 302 response code
  • Blocks .git, .env and every file whose name starts with a dot
  • Disables directory listings, sets UTF-8 as the default charset and points 404 to your own page
  • Keeps a folder out of search engines with an X-Robots-Tag header
  • Compresses responses, blocks access by IP address and by chosen HTTP methods

How to assemble the file

  1. Tick the rules you need — each one is added to the file in finished form
  2. Fill in the domain, the old and new paths, the response code and the path of your 404 page
  3. Read the finished file: every rule is separated by a comment explaining it
  4. Copy the text or download the file and place it in the site root

What the server does with the rules

Apache reads an .htaccess file while handling a request and applies it to the directory the file sits in and to every directory below. A file in the site root therefore governs the whole site, while the same file inside an uploads folder only governs that folder. The Require all denied and Require not ip directives arrived with Apache 2.4 and replaced the older Order deny,allow paired with Deny from all. Modules such as mod_deflate, mod_headers and mod_rewrite are enabled separately, which is why the generated file wraps their rules in IfModule: without the module, the block is simply skipped.

Ready rules and what each one does

What it doesDirectiveRequirements
Redirect www to the bare domainRewriteCond and RewriteRule with R=301mod_rewrite
Force HTTPSRewriteCond %{HTTPS} !=on and RewriteRulemod_rewrite, a certificate
Move an old pageRewriteRule with a 301 or 302 codemod_rewrite
Block .git and .envFilesMatch and Require all deniedApache 2.4, AllowOverride FileInfo
Disable directory listingsOptions -IndexesAllowOverride Options
Default charsetAddDefaultCharset UTF-8AllowOverride FileInfo
Keep a folder out of search resultsDirectoryMatch and Header set X-Robots-Tagmod_headers
Your own 404 pageErrorDocument 404 /404.htmlAllowOverride FileInfo
Compress responsesAddOutputFilterByType DEFLATEmod_deflate
Block by IP and by methodRequireAll and LimitExceptApache 2.4, AllowOverride Limit

The directives Require not ip and Require all denied exist in Apache 2.4 and later only.

Where .htaccess earns its place every day

The first scenario is a change of address. After a move to another domain the old links from search engines, from bookmarks and from articles stop working, and every one of them returns a 404. A RewriteRule with the 301 code sends the visitor to the new address and at the same time tells the search engine that the old address is no longer current. The second scenario is making addresses uniform: while a site opens under both example.com and www.example.com, a search engine sees two addresses for one document and splits the weight between them. A redirect towards one canonical form removes the problem.

The third scenario is technical and the most common around payments and internal services: keeping what should never reach the internet out of reach. A .git directory holding the full history of a repository, an .env file with database and mail passwords, database dumps and logs — none of that belongs in front of visitors, and one rule in the site root closes off such files at once. The fourth is a custom 404 page instead of the standard one: it keeps a visitor on the site and offers a link home. The same set of rules also serves during a move to a new CMS, when the old pages answer with a temporary placeholder.

  • A domain change and redirects from the old addresses
  • Reducing www and non-www to a single canonical address
  • Forced HTTPS without editing the main server configuration
  • Keeping .git, .env, dumps and logs away from strangers
  • Switching off file listings in directories
  • A custom 404 page and a folder kept out of search results

Where .htaccess files go wrong

The first mistake is losing a curly brace in RequireAll, FilesMatch or LimitExcept blocks. The closing brace sits on its own line and must end with a slash, otherwise Apache cannot tell where the block ends. The second mistake is writing two rules that contradict each other: a redirect from www and a redirect to www at the same time send the browser into a redirect loop and it reports an endless redirect. The third is forgetting that the Require directives only arrived with Apache 2.4, so the same idea on an older server is written differently.

Two further mistakes come from wrong expectations. The first is expecting an .htaccess file to protect a file stored higher up the tree: rules only apply downwards, so a file inside an uploads folder cannot block something in the site root. The second is assuming that an added X-Robots-Tag header keeps a folder out of search results while mod_headers is not loaded: the block is skipped silently and the folder stays open. Checking what ended up in the file is easier with a regular expression tester, and comparing two versions of a config is what the text comparison is for.

  • A missing trailing slash on the closing brace of a block
  • Redirects in both directions switched on at once
  • Require all denied syntax on Apache 2.2
  • Trying to protect a file above the directory holding the .htaccess
  • Counting on mod_headers when the module is not loaded
  • Forgetting to clear the browser cache when testing a redirect

A worked example: moving an old page

Take a concrete task: the address /old-page no longer works and the page has moved to /new-page. The rule is one line, a RewriteRule with a pattern, a substitution and flags. The pattern is compared against the request path without its leading slash, so it reads old-page, and the question mark at the end makes a trailing slash optional. The substitution is written the other way round, with a leading slash, because it is a finished address.

The R flag sets the response code and L stops processing: once the rule has fired, Apache does not look at the remaining lines of the file. Choose the code deliberately, with 301 for a permanent move and 302 for a temporary one. A pattern that starts with a caret is treated as a regular expression, and that is where escaping of dots starts to matter. The finished example is broken down in the table below, and the file itself can be taken from the code block and uploaded, provided the module check comes first.

What each part of the rule does

PartMeaningWhy it is there
RewriteEngine OnSwitches the module on in this fileWithout it the rules do nothing
RewriteCondA condition, for example on HTTP_HOSTNarrows a rule down to a host or a protocol
^old-page/?$The path pattern without a leading slashMatches /old-page and /old-page/
/new-pageWhere the visitor is sentWritten with a leading slash
R=301The response code301 for good, 302 for temporary
LStop processing the fileOtherwise a later rule may override the redirect
RewriteEngine On onceThe directive is not repeatedOne occurrence is enough per file
Test with a requestThe page answers 301 with a Location headerThe log shows which rule fired

After uploading, the browser may still show a cached response, so a redirect is best tested in a private window.

Apache, nginx and neighbouring tools

Before filling the file with rules, it is worth finding out which web server the hosting runs. Apache and LiteSpeed read .htaccess, nginx does not. Under nginx the same tasks are solved with the return, try_files and location directives in the server configuration, and without access to it the rules have to be handed over to the host. A separate check concerns the permissions of the file itself: a very common reason for the file being uploaded while nothing happens, and the permission calculator helps work out the mode.

When part of the job concerns the response code of the server rather than the configuration, the HTTP status code reference shows how a 301 differs from a 302 and what the server answers on an error. Blocking a folder from indexing in .htaccess duplicates a job that can be done at page level, where the noindex meta tag is put together by the meta tag generator. Breaking down the address that redirects point to is easier with a look at a URL broken into parts.

  • Working out the permissions of the configuration file
  • A reference of the codes a server can return
  • Why a particular HTTP error code appears
  • Assembling noindex meta tags for individual pages
  • Taking a page address apart
  • Testing the regular expressions used in the rules

Questions people ask about .htaccess

Where does the .htaccess file belong and what should it be called

The name has to be exactly .htaccess, with the leading dot and no extension, otherwise the server will not read it. Put it in the directory whose traffic it should govern: the site root next to index.php for site-wide rules, or inside a folder when the rules concern only that folder. The file is read on every request, so changes take effect without restarting the server. The web server user must be able to read it, usually with mode 644 — the details are covered in the piece on file permissions.

Why does the site return a 500 error after the file is uploaded

Three causes account for most cases. First, mod_rewrite is not enabled: Apache does not know the RewriteEngine directive and answers with Invalid command, and it does so on every request to the site. Second, httpd.conf carries AllowOverride None or allows only part of the directive set, and Apache replies that the directive is not permitted here. Third, there is a syntax error in the file itself, most often an unbalanced brace in a RequireAll block. Checking is straightforward: apachectl -M lists the loaded modules, and the error log names the exact line after an ordinary request to the page.

Does .htaccess work on nginx

No, and that is not a shortcoming of the generator but a fact about the server: nginx does not read .htaccess files at all, because it has no such directive. nginx rules live inside server and location blocks and look different: forced HTTPS becomes return 301 https://$host$request_uri, a single entry point becomes try_files $uri $uri/ /index.php, and blocking files is done with a location marked internal or with a rule on the extension. If the site runs on nginx, the rules have to be ported by hand, so it is worth checking which web server the hosting actually uses before writing anything.

What is the difference between a 301 and a 302 redirect

A 301 says the page has moved for good: browsers and search engines remember the new address and stop coming back. A 302 marks a temporary redirect, the address of the page does not change, and you should return to 301 once the event is over. Pick 301 for moved sections, a domain change or merged pages, and 302 for temporary landing pages, promotions and maintenance windows. The difference decides how a search engine carries the weight of the page over, and the HTTP status code reference alongside the piece on error codes explain the mechanics in more detail.

How do I switch off directory listings

A single directive, Options -Indexes, disables the automatic listing of a directory that has no index file: instead of a file list, the visitor gets a 403 error. The directive works per directory, so a rule in the site root switches listings off everywhere and one inside an uploads folder only affects that folder. The server has to permit it through AllowOverride Options, otherwise Apache refuses the directive as not allowed here. Turning listings off is worth doing on any public site, because without it the folder structure and the file names are visible to anyone who asks.

How do I block .git and .env

With a FilesMatch block holding a regular expression and the directive Require all denied, which arrived with Apache 2.4. The expression catches files whose name starts with a dot, that is .git, .env and .htaccess itself, as well as service extensions such as .sql, .log and .bak. One exception is worth keeping: .well-known holds the domain validation files and the certificate renewal files, and if the folder is blocked completely, automatic renewal of the HTTPS certificate stops working.

What does AddDefaultCharset UTF-8 actually do

It sets the default charset for responses where the encoding was not stated explicitly and adds the matching parameter to the Content-Type header. It does not replace a charset attribute inside the HTML: a page served as windows-1251 keeps being served that way. The directive helps when the application does not set the encoding itself, but relying on it alone is a mistake, because the output should always state its encoding. How encodings work and why UTF-8 became the standard is explained in the piece on UTF-8 and Unicode.

Why are some rules wrapped in IfModule

IfModule checks whether a module is loaded and skips the block if it is not. It is a safety net against the 500 error: without it an unknown directive takes the whole site down, with it the rule simply does not apply. The generated file wraps mod_deflate, which handles compression, and mod_headers, which provides the X-Robots-Tag header. The rules around RewriteEngine are deliberately left unwrapped, because if mod_rewrite is missing the site should say so straight away rather than quietly run without redirects — and that is checked with one command before uploading.

Related articles

Related tools