mod_rewrite cheat sheet and .htaccess tester

Runs in your browser

Paste your .htaccess and a URL: see which rule matches, what every condition compares and where Apache sends the request. Generate redirects for Apache and nginx, and look up every flag and variable. Nothing is uploaded.

Server settings
Waiting for rules

Paste an .htaccess on the left

Every rule and condition is evaluated the way Apache 2.4 does it, round by round.

How Apache got there

Default rules for your app

The .htaccess files that 41 popular projects ship, taken from their repositories (as of November 2026). Pick one to run it in the tester, or open the original.

Content management

  • Source
  • Source
  • Source
  • Source
  • Source
  • Source
  • Source
  • Source
  • Source
  • Source
  • Source
  • Source
  • Source
  • Source

Shops

  • Source
  • Source
  • Source
  • Source

Frameworks

Apps

Any site

  • Source

How mod_rewrite works

mod_rewrite is the Apache module that changes URLs on the fly: it redirects old addresses, serves pretty URLs from scripts and blocks requests. It reads rules from the server configuration or from .htaccess files.

^blog/(.*)$Pattern: a regular expression tested against the path. In .htaccess without the leading slash.
/news/$1Target: the new path or URL. $1 is the first (group) of the pattern, - means “no change”.
[R=301,L]Flags: how to apply it. Here: redirect with 301, then stop.
  1. Rules run top to bottom. For each rule, Apache tests the pattern first, against the path without the query string.
  2. Only if the pattern matches does it check the RewriteCond lines directly above that rule. They are ANDed unless a line has [OR]. A condition only belongs to the one rule after it.
  3. If everything matches, the target replaces the path, the flags apply, and the next rule sees the new path.
  4. In .htaccess, a changed path is an internal redirect: Apache starts a new round with the new path and runs the same rules again. That second round is where most loops come from. [END] or a condition stops it.
Switch mod_rewrite on
Debian, Ubuntu
sudo a2enmod rewrite
sudo systemctl restart apache2
httpd.conf
# Red Hat, Alma, Rocky: already in /etc/httpd/conf.modules.d/00-base.conf
LoadModule rewrite_module modules/mod_rewrite.so
Allow .htaccess
<Directory /var/www/html>
    AllowOverride FileInfo     # or All; with None, .htaccess rules are ignored silently
    Options FollowSymLinks     # mod_rewrite needs FollowSymLinks or SymLinksIfOwnerMatch
</Directory>
Is it loaded?
apachectl -M | grep rewrite     # rewrite_module (shared)
.htaccess or server config?
.htaccess (or <Directory>)VirtualHost / server config
The pattern seesblog/post (no leading slash, relative to the folder of the .htaccess)/blog/post
[L]ends this round; the rules run again on the resultstops, like [END]
RewriteBaseprefix for relative targets in subfoldersnot allowed
Speedread from disk on every requestread once at start
Changestake effect immediatelyneed a reload
A first rule

Turn the engine on once per file, then add rules. In .htaccess the pattern is matched against the path without the leading slash.

.htaccess
RewriteEngine On
RewriteRule ^hello$ /index.php?page=hello [L]

Redirects that work

Every example was run against a real Apache 2.4. Open one and press Test it, or use Generate a rule above for your own domain, with the nginx version next to it.

StatusUse for
301Moved permanentlyMoves you keep: new domain, HTTPS, new URLs. Browsers cache it, so test with 302 first.
302FoundTemporary: maintenance, tests, anything you’ll undo. Default of [R].
308Permanent, keeps the methodLike 301, but a POST stays a POST. APIs and forms.
307Temporary, keeps the methodLike 302 for POST requests.
Force HTTPS

%{REQUEST_URI} carries the path, Apache adds the query string by itself.

.htaccess
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Force HTTPS behind a proxy or CDN

Behind a load balancer Apache only sees plain HTTP. Ask the header the proxy sets, and write it as %{HTTP:X-Forwarded-Proto}. %{HTTP_X_FORWARDED_PROTO} is not a variable and is always empty.

.htaccess
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
www to non-www, and HTTPS in one hop

Two conditions joined with [OR], one redirect. Writing the host out keeps other subdomains untouched.

.htaccess
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [L,R=301]
non-www to www
.htaccess
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301]
Move a whole domain

Every path and the query string go along. Keep it for at least a year so rankings and old links move over.

.htaccess
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ [NC]
RewriteRule ^ https://new-domain.com%{REQUEST_URI} [L,R=301]
One page
.htaccess
RewriteEngine On
RewriteRule ^old-page\.html$ /new-page/ [L,R=301]
A whole folder

$1 is everything after the old folder.

.htaccess
RewriteEngine On
RewriteRule ^blog/(.*)$ /news/$1 [L,R=301]
Drop dates from old post URLs

From /2019/05/my-post/ to /blog/my-post/. \d{4} is a four-digit number.

.htaccess
RewriteEngine On
RewriteRule ^\d{4}/\d{2}/([^/]+)/?$ /blog/$1/ [L,R=301]
Remove index.php or index.html from URLs

Matches only what the browser asked for (%{THE_REQUEST}), so the internal request for the index file doesn’t loop.

.htaccess
RewriteEngine On
RewriteCond %{THE_REQUEST} \s/+(.*/)?index\.(php|html?)[\s?] [NC]
RewriteRule ^ /%1 [L,R=301,NE]
Remove the trailing slash

Real folders keep their slash, otherwise mod_dir would add it back and the two would loop.

.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
Add the trailing slash
.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(/|\.[a-zA-Z0-9]{1,5})$
RewriteRule ^ %{REQUEST_URI}/ [L,R=301]

Without mod_rewrite: Redirect 301 /old /new (mod_alias) also moves everything below /old/ and keeps the query string. It runs after all RewriteRules, so don’t mix both for the same paths.

Pretty URLs and front controllers

Without [R], the browser keeps its address and Apache quietly serves another file. That is how CMSs and frameworks route every request through one script.

Front controller

Files and folders that exist are served as they are, everything else goes to index.php. [END] stops for good; with [L] Apache would run the rules again for index.php.

.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [END]
The same without mod_rewrite

FallbackResource (mod_dir, Apache 2.4.2 and later) sends every request that doesn’t hit a file to one script.

.htaccess
FallbackResource /index.php
Pretty URLs

The visitor sees /product/42, the script gets ?id=42. [QSA] keeps extra parameters.

.htaccess
RewriteEngine On
RewriteRule ^product/([0-9]+)/?$ product.php?id=$1 [QSA,END]
URLs without .php

The first rule sends old links with .php to the short address, the second serves the short address from the .php file.

.htaccess
RewriteEngine On
RewriteCond %{THE_REQUEST} \s/+(.+?)\.php[\s?] [NC]
RewriteRule ^ /%1 [R=301,NE,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [END]
Keep .html URLs, run PHP

Old .html addresses stay the same while a .php file of the same name answers.

.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)\.html$ $1.php [END]
Language prefix

The language and the rest of the path become parameters. [B] escapes the path so a space or & can’t break the query string.

.htaccess
RewriteEngine On
RewriteRule ^(de|en|fr)/(.*)$ index.php?lang=$1&path=$2 [B,QSA,END]
Serve a framework from /public on shared hosting

When you can’t point the DocumentRoot at /public, send everything there. The app folder and .env become unreachable. The condition stops the second round; [END] would break the start page, because the DirectoryIndex lookup runs the rules again as a sub-request.

.htaccess
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(.*)$ public/$1 [L]

Query strings

The pattern of a RewriteRule never sees the part after the ?. Test it with RewriteCond %{QUERY_STRING} and control it with ?, [QSA] and [QSD].

React to a parameter

The pattern of RewriteRule never sees the query string. Test it with %{QUERY_STRING}; %1 is the captured value. The ? at the end drops the old query.

.htaccess
RewriteEngine On
RewriteCond %{QUERY_STRING} (?:^|&)id=(\d+)(?:&|$)
RewriteRule ^product\.php$ /product/%1? [L,R=301]
Remove the whole query string
.htaccess
RewriteEngine On
RewriteCond %{QUERY_STRING} .
RewriteRule ^ %{REQUEST_URI} [QSD,L,R=301]
Remove one parameter (fbclid)

Two conditions for “first parameter” and “somewhere later”; the rest of the query stays. [NE] keeps the query as it was sent. Works for plain ASCII paths.

.htaccess
RewriteEngine On
RewriteCond %{QUERY_STRING} ^fbclid=[^&]*&?(.*)$ [NC,OR]
RewriteCond %{QUERY_STRING} ^(.+?)&fbclid=[^&]*(.*)$ [NC]
RewriteRule ^ %{REQUEST_URI}?%1%2 [NE,L,R=301]
Replace, append or drop

A ? in the target replaces the visitor’s query, [QSA] appends it, a ? at the very end or [QSD] drops it. Without ? in the target the query is passed on unchanged.

.htaccess
RewriteEngine On
RewriteRule ^a/(.*)$ search.php?q=$1 [END]
RewriteRule ^b/(.*)$ search.php?q=$1 [QSA,END]
RewriteRule ^c/(.*)$ search.php? [END]
RewriteRule ^d/(.*)$ search.php [END]
Spaces and & in captured paths: [B]

Back-references are decoded. Without [B], /search/a%20b would put a raw space into the query, which Apache refuses with 403 since 2.4.56.

.htaccess
RewriteEngine On
RewriteRule ^search/(.*)$ search.php?q=$1 [B,END]

Blocking requests and staying safe

mod_rewrite can block, but Require and <FilesMatch> are often simpler, and the tester evaluates both. For a password, create the line with the htpasswd generator.

Hidden files and backups

/.well-known/ stays reachable for Let’s Encrypt. Better still: keep such files out of the web root.

.htaccess
RewriteEngine On
RewriteRule "(^|/)\.(?!well-known/)" - [F]
RewriteRule \.(sql|bak|old|swp|log)$ - [F,NC]
Block user agents

Only stops polite bots; the User-Agent is easy to fake. For addresses, “Require not ip …” is the cleaner tool.

.htaccess
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} (ahrefsbot|mj12bot|python-requests) [NC]
RewriteRule ^ - [F]
Lock wp-login.php to one IP address
.htaccess
RewriteEngine On
RewriteCond %{REMOTE_ADDR} !=203.0.113.7
RewriteRule ^wp-login\.php$ - [F]
Maintenance mode with 503

503 tells search engines to come back later. Your own IP still sees the site; the page and its CSS stay reachable.

.htaccess
ErrorDocument 503 /maintenance.html
RewriteEngine On
RewriteCond %{REMOTE_ADDR} !=203.0.113.7
RewriteCond %{REQUEST_URI} !^/(maintenance\.html|assets/)
RewriteRule ^ - [R=503,L]
Pass the Authorization header to PHP

With PHP-FPM or CGI, Apache doesn’t hand the Authorization header to PHP. This copies it into HTTP_AUTHORIZATION; WordPress and Laravel ship the same line.

.htaccess
RewriteEngine On
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

Security changes in Apache 2.4

  • 2.4.56: no raw spaces in the query. A rewrite that puts a space or control character into the query string now gets 403. Escape back-references with [B].
  • 2.4.60: encoded question marks. If $1 or a variable contains a “?” that came from %3F in the request, the rewrite is refused with 403 (CVE-2024-38474). [UnsafeAllow3F] allows it again where it can’t be abused.
  • 2.4.60: targets that look like file paths. In the server config, a target starting with $1 or a variable is no longer used as a file system path (CVE-2024-38475). [UnsafePrefixStat] restores the old behavior.
  • 2.4.67 and 2.4.69: shared hosting. 2.4.67 fixed a bug that let .htaccess authors read files through expressions (CVE-2026-24072), 2.4.69 a use-after-free with look-ahead variables like %{LA-U:HTTP:…} (CVE-2026-56154). Run a current 2.4.
  • [P] and user input. If any part of a proxy target comes from the request, an attacker can make your server fetch other hosts (SSRF). Write scheme and host out.

RewriteRule flags

Flags go in square brackets after the target, separated by commas: [R=301,L]. They are not case-sensitive, and each has a short and usually a long name.

FlagWhat it does
[L]lastStop this pass through the rules.In .htaccess the rules run again on the result, see [END].
[END]Stop, and no further pass in .htaccess either.Apache 2.3.9+. The safe choice for internal rewrites in .htaccess.
[R=301]redirectSend an external redirect. Without a number: 302. Also R=permanent, temp, seeother.Add L, otherwise the next rules keep working on the redirect URL. R=4xx/5xx answers with that status instead.
[NC]nocaseCase-insensitive pattern.
[QSA]qsappendAppend the original query string to the one in the target.Without QSA, a ? in the target replaces the query.
[QSD]qsdiscardDrop the original query string.Apache 2.4.0+. Takes precedence over QSA.
[QSL]qslastSplit the target at the last ? instead of the first.Apache 2.4.19+.
[NE]noescapeDon’t %-encode the target of a redirect.Needed for #anchors and for targets that are already encoded.
[B]Escape back-references ($1, %1) before they go into the target.B=chars escapes only those characters (2.4.26+). Use it when $1 goes into a query string.
[BNP]backrefnoplusWith B: write a space as %20 instead of +.Apache 2.4.26+. For back-references in the path.
[BCTLS]Escape only control characters and spaces in back-references.Apache 2.4.57+.
[BNE=chars]Characters that B and BCTLS leave alone, e.g. BNE=/.Apache 2.4.57+.
[F]forbiddenAnswer 403 Forbidden. Use - as target.Implies L.
[G]goneAnswer 410 Gone. Use - as target.Implies L.
[C]chainChain to the next rule: if this one doesn’t match, the chained rules are skipped.
[S=n]skipSkip the next n rules if this one matches.An if/else for rules; <If> is often clearer.
[N]nextStart the rules again from the top with the result.Stops with 500 after 10,000 passes (2.4.8+); N=32000 sets another limit.
[PT]passthroughPass the result on to Alias, ScriptAlias and other mappers.Server config only; implied in .htaccess.
[P]proxyFetch the target through mod_proxy.Needs mod_proxy. Never build the host from user input (SSRF).
[E=VAR:val]envSet an environment variable. E=!VAR unsets it.After an internal redirect it is called REDIRECT_VAR.
[CO=…]cookieSet a cookie: CO=name:value:domain:minutes:path:secure:httponly:samesite.samesite since 2.4.47.
[T=type]typeForce the MIME type of the response.
[H=handler]HandlerForce a handler, e.g. H=application/x-httpd-php.
[DPI]discardpathDrop PATH_INFO from the result.Prevents doubled path info when several rules rewrite in .htaccess.
[NS]nosubreqSkip this rule for internal sub-requests (DirectoryIndex lookups, SSI).
[UnsafeAllow3F]Allow a rewrite that turns an encoded %3F from $1 or a variable into a real “?”.Apache 2.4.60+ refuses such rewrites with 403 by default (CVE-2024-38474).
[UnsafePrefixStat]Allow a server-config target that starts with $1 or a variable to be a file system path.Apache 2.4.60+ (CVE-2024-38475).
[UNC]Windows only: keep a leading // for UNC paths.Apache 2.4.63+.

Conditions

RewriteCond TestString CondPattern [flags]. The test string usually is a variable like %{HTTP_HOST}. Every condition belongs to the next RewriteRule only.

TestTrue if
regex^www\.The test string matches the regular expression. ! in front negates any test.
=text=on, =""Exactly equal. ="" tests for an empty string.
<text, >text, <=text, >=text>=20260101Compare as strings. Careful: Apache compares the length first, so 9 < 10.
-eq, -ne, -lt, -le, -gt, -ge-lt10 or "-lt 10"Compare as whole numbers. Write the number right after the operator, or put both in quotes; with a space in between, Apache reads the number as flags and fails.
-f, -s%{REQUEST_FILENAME} !-fIs a regular file (-s: and not empty).
-d%{REQUEST_FILENAME} !-dIs a folder.
-l (-L, -h)Is a symbolic link.
-xHas execute permission.
-F, -UIs a file or URL that a sub-request may access. Slow: each test runs a sub-request.
exprRewriteCond expr "%{HTTP_HOST} =~ /^www\./"An Apache expression (ap_expr), like in <If>.
  • [NC] ignores case, [OR] joins the condition with the next one, [NV] keeps a header out of the Vary header.
  • $1 to $9 come from the pattern of the rule (it is tested first), %1 to %9 from the last condition that matched. $0 and %0 are the whole match.
  • With [OR], the first true condition of a group wins and the rest of the group is skipped.

Server variables

Use them as %{NAME} in conditions and targets. Values below are for https://example.com/blog/caf%C3%A9?page=2.

Request
VariableExample and notes
%{REQUEST_URI}/blog/caféThe path, already %-decoded, without query string. In a second round it is the rewritten path.
%{QUERY_STRING}page=2&sort=newEverything after the ?, as sent (not decoded).
%{THE_REQUEST}GET /blog/caf%C3%A9?page=2 HTTP/1.1The request line as the browser sent it, not decoded. Never changes, so it tells old links from internal rewrites.
%{REQUEST_METHOD}GET
%{REQUEST_SCHEME}https
%{HTTPS}on“on” or “off”. Behind a proxy it is off; then ask %{HTTP:X-Forwarded-Proto}.
%{HTTP_HOST}example.comThe Host header, with :port if the browser sent one.
%{HTTP_USER_AGENT} %{HTTP_REFERER} %{HTTP_COOKIE} %{HTTP_ACCEPT}These four headers have names of their own.
%{HTTP:Header-Name}%{HTTP:X-Forwarded-Proto}Any other request header. %{HTTP_X_FORWARDED_PROTO} is not a variable and stays empty.
%{REMOTE_ADDR}203.0.113.7The visitor’s IP, or the proxy’s if you don’t use mod_remoteip.
Files and server
VariableExample and notes
%{REQUEST_FILENAME}/var/www/html/blog/caféIn .htaccess: the file or folder Apache mapped the URL to, what -f and -d test. For a path that doesn’t exist it ends at the first missing part; the rest is PATH_INFO. Same as SCRIPT_FILENAME.
%{DOCUMENT_ROOT}/var/www/html
%{PATH_INFO}/extraWhat follows a real file, as in /index.php/extra.
%{SERVER_NAME}example.com
%{SERVER_PORT}443
%{SERVER_ADDR}192.0.2.10
%{IS_SUBREQ}false“true” for internal sub-requests.
Environment
VariableExample and notes
%{ENV:VAR}%{ENV:REDIRECT_STATUS}An environment variable, e.g. one set with [E=…]. REDIRECT_STATUS is empty in the first round and 200 after an internal redirect.
%{SSL:VAR}%{SSL:SSL_PROTOCOL}mod_ssl variables, empty without mod_ssl.
Time
VariableExample and notes
%{TIME_YEAR} %{TIME_MON} %{TIME_DAY}2026, 11, 27Two digits for month and day.
%{TIME_HOUR} %{TIME_MIN} %{TIME_SEC}14, 05, 09Server time zone.
%{TIME_WDAY}50 = Sunday.
%{TIME}20261127140509

Why your rule does nothing, or too much

Nothing happens at all

AllowOverride None in the server config makes Apache ignore .htaccess silently. Test with a line of garbage: if the site doesn’t answer 500, the file isn’t read.

^/ never matches

In .htaccess the path has no leading slash. Write ^blog/, or use RewriteCond %{REQUEST_URI} ^/blog/ for the full path.

ERR_TOO_MANY_REDIRECTS

The target matches the rule again, or two rules send the browser back and forth. Behind a proxy, %{HTTPS} is always off: check %{HTTP:X-Forwarded-Proto}.

500 after a rewrite

A loop of internal redirects ([L] doesn’t stop the next round in .htaccess, use [END]), or a syntax error: unknown flag, broken regex, a # comment after the target. The tester names the line.

Conditions ignored

A RewriteCond only applies to the next RewriteRule. Repeat the conditions, or use [S=n] or .

/var/www/html in the redirect

A relative target with [R] gets the folder on disk as prefix. Start the target with / or add RewriteBase /.

403 for some URLs

Since 2.4.56/2.4.60 Apache refuses raw spaces in the new query string and a “?” coming from %3F. Add [B], or [UnsafeAllow3F] where it’s safe. A Require or Deny line can also be the cause.

500 with php_value

php_value and php_flag only work with mod_php. With PHP-FPM, which most hosts use, Apache answers 500. Use .user.ini or wrap them in .

Folder adds a slash anyway

mod_dir redirects /folder to /folder/ (DirectorySlash On) even after an internal rewrite. Exclude real folders with RewriteCond %{REQUEST_FILENAME} !-d.

Old redirect still there

Browsers cache 301 redirects. Test with curl or a private window, and use 302 while you build.

The classic loop

In .htaccess, [L] only ends one pass. Apache then runs the rules again on /app.php/a, which matches ^(.*)$ again, until it gives up after 10 rounds with a 500.

.htaccess
RewriteEngine On
RewriteRule ^(.*)$ /app.php/$1 [L]
Relative target without RewriteBase

A redirect to a relative target gets the folder on disk as prefix. Start the target with / or set RewriteBase /.

.htaccess
RewriteEngine On
RewriteRule ^old$ new [R=301,L]
403 for an encoded question mark

Since Apache 2.4.60, a “?” that comes out of $1 or a variable is refused (CVE-2024-38474). Add [UnsafeAllow3F] only where that’s harmless.

.htaccess
RewriteEngine On
RewriteRule ^go/(.*)$ /page.php/$1 [L]

See what Apache does

curl
curl -sI https://example.com/old-page         # status and Location only
curl -sIL --max-redirs 10 http://example.com/   # follow the whole chain
Rewrite log
# Server config or VirtualHost (not .htaccess). trace3 is plenty, trace8 shows everything.
LogLevel alert rewrite:trace3

# Then watch the error log:
tail -f /var/log/apache2/error.log | grep '\[rewrite:'
Syntax check
apachectl configtest      # server config; .htaccess errors only show up per request

The same in nginx

nginx has no .htaccess and no RewriteCond. Most mod_rewrite rules turn into return, rewrite or try_files. The generator above writes both versions; here is the mapping.

Apachenginx
RewriteRule ^old$ /new [R=301,L]location = /old { return 301 /new$is_args$args; }nginx drops the query string on return unless you append it.
RewriteRule ^blog/(.*)$ /news/$1 [R=301,L]rewrite ^/blog/(.*)$ /news/$1 permanent;nginx patterns start with /. permanent = 301, redirect = 302.
RewriteCond %{REQUEST_FILENAME} !-f + !-d + front controllertry_files $uri $uri/ /index.php?$query_string;
RewriteRule … [L] (internal)rewrite … last;break stays in the same location.
[NC]~* instead of ~, or (?i)
[QSA]automaticnginx appends the old query to a new one; end the target with ? to drop it.
%{HTTP_HOST}$host (no port) or $http_host
%{REQUEST_URI}$uri (decoded) or $request_uri$request_uri is raw and includes the query string.
%{QUERY_STRING}$args
%{HTTPS} offa separate server { listen 80; } blockCheaper than an if in every request.
%{HTTP:X-Forwarded-Proto}$http_x_forwarded_proto
.htaccessno equivalentAll rules live in the server config; reload with nginx -s reload.

Questions about mod_rewrite

What is mod_rewrite?

An Apache module that rewrites requested URLs with regular expressions. It powers redirects (301, 302), pretty URLs like /product/42 and the front controllers of WordPress, Laravel and most PHP frameworks.

How do I enable mod_rewrite?

On Debian and Ubuntu run sudo a2enmod rewrite and restart Apache. For .htaccess rules, the server config must also allow them with AllowOverride FileInfo (or All) for that folder.

What is the difference between [L] and [END]?

Both stop the current pass. In .htaccess, Apache then starts over with the rewritten path and runs the rules again; [L] allows that second round, [END] stops for good. In the server config they behave the same.

Why does my rule cause too many redirects?

The redirect target matches the same rule again, or two rules (for example https and www) send the browser back and forth. Exclude the target with a RewriteCond, combine both into one redirect, and behind a proxy test %{HTTP:X-Forwarded-Proto} instead of %{HTTPS}.

Why do I get 403 Forbidden after an Apache update?

Apache 2.4.56 refuses rewrites that put raw spaces into the query string (fix: [B]), and 2.4.60 refuses a “?” that comes from an encoded %3F in $1 or a variable (fix: [UnsafeAllow3F] where safe). The tester above shows which rule causes it.

Does the order of the rules matter?

Yes. Rules run top to bottom and each one sees the result of the ones before. Put redirects first, then internal rewrites, and the front controller last.

Should I use 301 or 302?

Use 301 (or 308) for moves you keep, like a new domain or HTTPS. Browsers cache it hard, so test with 302 and switch to 301 when everything works.

Can I test rewrite rules without a server?

Yes: paste them into the tester at the top of this page. It follows Apache 2.4 step by step, runs entirely in your browser, and was checked against a real Apache with hundreds of requests.

This cheat sheet used to live at mod-rewrite-cheatsheet.com. Old links land here, anchors included. The tester was checked against a real Apache 2.4 with the default .htaccess of the projects above, broken variants of them, and hundreds of single requests.

Searches the list of pages on this site. What you type stays in your browser.