mod_rewrite is the most powerful and most misused module in Apache. Most production rule sets we audit have three rules that do real work and twelve copy-pasted from a 2008 forum that either no-op or contradict each other. This article is the mental model and the small set of patterns that handle 90% of legitimate use cases — canonical hostname enforcement, HTTPS redirects, front-controller routing, and pretty URLs.
How to verify
Confirm the module is loaded and active in the scope you care about. Rewrite rules in .htaccess need AllowOverride to include FileInfo; rules in the vhost just need RewriteEngine On:
apachectl -M | grep rewrite
grep -r 'RewriteEngine' /etc/apache2/sites-enabled/ /etc/apache2/conf-enabled/
sudo apache2ctl -t -D DUMP_RUN_CFG
curl -sI -H 'Host: example.com' http://127.0.0.1/old-path
For debugging, enable rewrite tracing in the vhost. LogLevel alert rewrite:trace3 writes every rule evaluation to the error log — extremely verbose, only enable temporarily:
LogLevel alert rewrite:trace3
What’s happening
mod_rewrite evaluates rules in order, per request, against the URL path (not the full URL by default). Each RewriteRule is a pattern + substitution + optional flags. Each RewriteCond is a guard that scopes the next RewriteRule to a specific condition (matching headers, query strings, server variables).
Two scopes matter:
- Vhost scope — rules in
<VirtualHost>or<Directory>are parsed once at startup and execute against the URL path with no leading slash for the per-directory case, with leading slash in vhost scope. Faster, statically loadable. .htaccessscope — rules in a.htaccessfile are parsed for every request that touches the directory tree. Slower, but lets app deployments ship rules without server config changes.
The flags ([L], [R=301], [NC], [QSA], [E=VAR:val]) modify rule behavior:
[L]— last rule for this pass; stop processing the current ruleset.[R=301]or[R=302]— emit an HTTP redirect with the given status code.[NC]— case-insensitive pattern match.[QSA]— append the original query string to the substitution.[END]— like [L] but also stops.htaccessre-entry, which.htaccessrules need to truly terminate.
The procedure
The patterns below cover most real-world rewrites. Drop them in the vhost, not in .htaccess, when you control the server config.
-
Force HTTPS redirect. Run inside the port-80 vhost or use a single port-80 vhost that only does this redirect for every site:
RewriteEngine On RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]When Apache is behind a TLS-terminating load balancer, use
%{HTTP:X-Forwarded-Proto}instead of%{HTTPS}. -
Canonical hostname (apex vs www). Pick one and redirect the other:
RewriteEngine On RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC] RewriteRule ^(.*)$ https://example.com/$1 [R=301,L] -
Strip trailing slash. Useful for SEO consistency:
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.+)/$ /$1 [R=301,L]The condition excludes real directories — otherwise you redirect
/blog/to/blogand break directoryindex.htmlserving. -
Front-controller pattern (WordPress, Laravel, Symfony). Route all non-file requests to
index.php:RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L]The
!-fand!-dconditions stop the rule from rewriting requests for actual files (CSS, images, uploaded assets). -
Path-based legacy URL migration. A site moved from
/articles/123-old-slugto/blog/old-slug:RewriteRule ^articles/[0-9]+-(.+)$ /blog/$1 [R=301,L]The captured group
(.+)becomes$1in the substitution. -
Block requests with specific user agents. Cheap bot filter — paired with proper rate limiting, not a substitute for it:
RewriteCond %{HTTP_USER_AGENT} (bot1|bot2|bot3) [NC] RewriteRule .* - [F,L][F]returns 403 Forbidden. The substitution-means “do not change the URL”. -
Maintenance mode flag. Drop a file
/var/www/.maintenanceto flip the site into a holding page without a config reload:RewriteCond /var/www/.maintenance -f RewriteCond %{REQUEST_URI} !^/maintenance.html$ RewriteCond %{REQUEST_URI} !^/static/ RewriteRule .* /maintenance.html [R=503,L]R=503is the right status code for planned maintenance — search engines treat 503 as transient.
After any rule changes, configtest and reload. The error log under rewrite:trace3 is the only practical debugger; ship it through Loki or grep it inline.
Common pitfalls
- Rules in
.htaccessuse a different leading-slash convention than rules in vhost scope — the pattern that works in vhost may need a leading-slash strip in.htaccess. Test both contexts explicitly. [R]without a status code defaults to[R=302]. Always specifyR=301for permanent moves; otherwise search engines treat the redirect as temporary.RewriteCondonly applies to the nextRewriteRule— multiple conditions in a row are AND-ed before the rule. To OR conditions, use[OR]on each one except the last.- Rules that match all paths (
^(.*)$) at the top of a vhost can shadow more specific rules below — order matters. Put redirects before rewrites, terminators before catch-alls. - The
RewriteLogdirective is gone in Apache 2.4 — debug viaLogLevel alert rewrite:trace3written into the error log. Forgetting this and searching for a separate rewrite log is a half-hour wasted.
Stack Harbor manages Apache rewrite rule sets as reviewable, tested artifacts — every rule has a comment explaining what it does, every change is configtested before reload, and the rule set is small enough to fit in one screen. If your inherited rewrite block has crossed 50 lines and nobody is sure which rules are still doing anything, see how that audit fits into Managed Operations.