mod_rewrite

On this page 7

mod_rewrite is the Apache HTTP Server module that rewrites request URLs on the fly using regular expressions, conditions and flags. Among web servers, it is the classic tool for turning a requested address into a different internal file path, issuing redirects, enforcing HTTPS or a canonical host name, and routing every request of a framework through a single front controller.

The module evaluates rules written with the directives RewriteRule and RewriteCond, either in the main server configuration or in per-directory .htaccess files. Because it can change a URL before Apache maps it to the file system, mod_rewrite separates the public structure of a site from the way its files are actually stored.

How mod_rewrite processes a request

mod_rewrite works by matching the requested URL path against a pattern and, when it matches, substituting a new target. The engine runs only when RewriteEngine On is set for the relevant context, and it walks through the rules in the order they are written.

Each RewriteRule has three parts: a pattern (a Perl-compatible regular expression), a substitution (the new path or URL) and optional flags in square brackets. One or more RewriteCond lines placed directly above a rule act as preconditions; the rule fires only if all of them are true. Conditions can test server variables such as %{HTTP_HOST}, %{HTTPS}, %{REQUEST_URI} or whether a requested file exists.

A subtle point is the order of evaluation: Apache first tries the rule pattern, and only if it matches does it evaluate the conditions above it. Captured groups are available as $1 to $9 from the rule and %1 to %9 from the last matched condition, which lets a substitution reuse parts of the original request.

The table below lists the directives that make up a typical rule set.

DirectivePurposeExample use
RewriteEngineTurns rule processing on or offRewriteEngine On
RewriteRuleMatches a pattern and defines the substitutionMap /blog/42 to index.php?id=42
RewriteCondAdds a condition the next rule must satisfyApply a rule only when HTTPS is off
RewriteBaseSets the URL prefix for relative substitutions in .htaccessRewriteBase /shop/
RewriteMapLooks up substitutions in an external mapTranslate legacy product codes to new slugs
RewriteOptionsControls inheritance of rules between contextsInherit parent rules into a virtual host
Core mod_rewrite directives

Rewrite flags and what they change

Flags modify how a matched rule behaves, and choosing the wrong flag is the most common source of broken rule sets. They are written as a comma-separated list, for example [R=301,L].

FlagMeaningTypical effect
LLast rule in this passStops processing further rules for the current round
ENDStop rewriting completelyPrevents any further rounds, unlike L in .htaccess
R=301External permanent redirectBrowser and search engines update to the new URL
R=302External temporary redirectBrowser follows, but the old URL stays canonical
NCNo casePattern matching ignores letter case
QSAQuery string appendKeeps original query parameters alongside new ones
PProxyPasses the request to mod_proxy as a reverse proxy
FForbiddenReturns HTTP 403 for matching requests
Frequently used RewriteRule flags

The difference between internal rewrites and external redirects is fundamental. An internal rewrite changes which resource Apache serves while the browser address bar stays the same. An external redirect, triggered by the R flag or a full URL with a different host, sends an HTTP 3xx response so the client requests the new address itself.

Server configuration versus .htaccess

mod_rewrite rules behave differently depending on where they are placed. In the server or virtual host configuration they are read once at startup and match the full URL path. In .htaccess files they are read on every request, and the directory prefix is stripped before matching, so a pattern such as ^blog/ must omit the leading slash.

AspectVirtual host configurationPer-directory .htaccess file
PerformanceParsed once at startupRead and parsed on every request
Pattern matchingFull path with leading slashPath relative to the directory
Required permissionServer administrator accessAllowOverride FileInfo enabled
Reload needed after editsYes, graceful restartNo, changes apply immediately
Looping riskLowerHigher, because rules rerun after internal rewrites
Placement contexts compared

In per-directory context, an internal rewrite causes Apache to reprocess the request from the start, which is why the L flag alone does not prevent loops there. Administrators who control the server should prefer the main configuration for both speed and predictability, and keep .htaccess for shared hosting where it is the only option.

Typical uses and equivalents on other web servers

Most production rule sets solve a small number of recurring routing problems. Content management systems such as WordPress ship a short block that sends every request for a non-existing file to index.php, which is the front controller pattern.

  • Clean URLs: mapping /products/red-shoes to a script with query parameters.
  • Forcing HTTPS: redirecting plain HTTP requests with a 301 when %{HTTPS} is off.
  • Canonical host: sending example.com to www.example.com or the reverse.
  • Legacy redirects: preserving search rankings after a site migration.
  • Access control: blocking requests by user agent, referrer or path pattern.

Other servers implement the same ideas with different syntax and semantics, which matters when migrating a site away from Apache.

ServerRewriting mechanismReads .htaccess
Apache HTTP Servermod_rewrite with RewriteRule and RewriteCondYes
Nginxrewrite, return and try_files in server blocksNo
LiteSpeed Web ServerApache-compatible rewrite engineYes
OpenLiteSpeedApache-compatible rules, loaded at restartPartially
Caddyrewrite, redir and try_files directivesNo
Microsoft IISURL Rewrite module with XML rulesNo
URL rewriting across web servers

Common mistakes and debugging

The most frequent failures are infinite redirect loops, rules that never match because of a leading slash, and redirects cached permanently by browsers. Testing with R=302 before switching to R=301 avoids the last problem, because browsers cache permanent redirects aggressively.

Since Apache 2.4, rule processing is traced with LogLevel alert rewrite:trace3 (levels up to trace8), which writes each pattern match and substitution to the error log. The older RewriteLog directive no longer exists. Trace logging is verbose and should never stay enabled in production.

The Apache documentation itself notes that many tasks do not need mod_rewrite at all. A simple redirect is clearer with Redirect or RedirectMatch from mod_alias, and routing to a front controller is often handled by FallbackResource. Using the simplest directive keeps configurations easier to audit and faster to execute.

Put simply

mod_rewrite is a set of forwarding instructions for an Apache web server. When a visitor asks for one address, the server can quietly deliver a different file, or tell the browser to go somewhere else.

It works like a mailroom clerk with a list of rules. Letters for an old department go to the new one. Letters with a short, friendly address reach the right desk. Visitors see neat, readable web addresses. The files behind them can be organized however the developers like.

In practice

An online bookstore moves from an old catalog script to a new system. Old links look like /catalog.php?item=1234, while new pages use addresses such as /books/1234-the-old-man-and-the-sea. Thousands of external links and search results still point to the old format.

The administrator adds a RewriteMap that translates each item number to its new slug and a single rule with a RewriteCond on the query string that issues a 301 redirect to the matching new page. A second rule forces every request to HTTPS on the www host. After two weeks of testing with temporary redirects, the team switches to permanent ones; search engines update their index over the following weeks and the store keeps its organic traffic through the migration.