Build Apache .htaccess rules without memorizing mod_rewrite
The .htaccess file is a per-directory configuration file that Apache reads on
every request, letting you change server behaviour without touching the main
config. This builder generates the most common production rules — forcing HTTPS,
canonicalizing the www prefix, custom error pages, trailing-slash handling,
directory-listing control, and a baseline set of security headers — and outputs
a single copy-ready block.
How it works
Most redirect and rewrite logic uses the mod_rewrite engine. A typical HTTPS
redirect inspects the %{HTTPS} server variable and issues a 301 redirect to the
https:// version of the requested URL:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
The RewriteCond is a guard — the following RewriteRule only fires when the
condition matches. The R=301 flag makes it a permanent redirect (good for SEO),
and L stops processing further rules. Canonical www/non-www redirects use a
%{HTTP_HOST} condition to match the unwanted host and rewrite to your chosen
canonical domain. Error pages use the simpler ErrorDocument directive, and
security headers use mod_headers with Header set directives wrapped in an
IfModule guard so the file is safe even if the module is absent.
Tips and notes
- Put redirect and canonicalization rules near the top, before any app rewrites (for example a front-controller rule), so visitors land on the canonical URL before deeper routing runs.
- A
500 Internal Server Erroron the whole directory almost always means an.htaccesssyntax error — comment out blocks to bisect the problem. - Wrap optional modules in
<IfModule mod_headers.c>so a missing module degrades gracefully instead of throwing a 500. .htaccessis read on every request and is slower than equivalent directives in the main config; on a server you control, prefer the vhost where possible.