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.
| Directive | Purpose | Example use |
|---|---|---|
| RewriteEngine | Turns rule processing on or off | RewriteEngine On |
| RewriteRule | Matches a pattern and defines the substitution | Map /blog/42 to index.php?id=42 |
| RewriteCond | Adds a condition the next rule must satisfy | Apply a rule only when HTTPS is off |
| RewriteBase | Sets the URL prefix for relative substitutions in .htaccess | RewriteBase /shop/ |
| RewriteMap | Looks up substitutions in an external map | Translate legacy product codes to new slugs |
| RewriteOptions | Controls inheritance of rules between contexts | Inherit parent rules into a virtual host |
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].
| Flag | Meaning | Typical effect |
|---|---|---|
| L | Last rule in this pass | Stops processing further rules for the current round |
| END | Stop rewriting completely | Prevents any further rounds, unlike L in .htaccess |
| R=301 | External permanent redirect | Browser and search engines update to the new URL |
| R=302 | External temporary redirect | Browser follows, but the old URL stays canonical |
| NC | No case | Pattern matching ignores letter case |
| QSA | Query string append | Keeps original query parameters alongside new ones |
| P | Proxy | Passes the request to mod_proxy as a reverse proxy |
| F | Forbidden | Returns HTTP 403 for matching requests |
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.
| Aspect | Virtual host configuration | Per-directory .htaccess file |
|---|---|---|
| Performance | Parsed once at startup | Read and parsed on every request |
| Pattern matching | Full path with leading slash | Path relative to the directory |
| Required permission | Server administrator access | AllowOverride FileInfo enabled |
| Reload needed after edits | Yes, graceful restart | No, changes apply immediately |
| Looping risk | Lower | Higher, because rules rerun after internal rewrites |
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-shoesto a script with query parameters. - Forcing HTTPS: redirecting plain HTTP requests with a 301 when
%{HTTPS}is off. - Canonical host: sending
example.comtowww.example.comor 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.
| Server | Rewriting mechanism | Reads .htaccess |
|---|---|---|
| Apache HTTP Server | mod_rewrite with RewriteRule and RewriteCond | Yes |
| Nginx | rewrite, return and try_files in server blocks | No |
| LiteSpeed Web Server | Apache-compatible rewrite engine | Yes |
| OpenLiteSpeed | Apache-compatible rules, loaded at restart | Partially |
| Caddy | rewrite, redir and try_files directives | No |
| Microsoft IIS | URL Rewrite module with XML rules | No |
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.