Skip to content

Menu

.htaccess Cheat Sheet: Redirects, RewriteRule, Headers and Access

Checked against Apache HTTP Server Apache httpd 2.4.71 docs (released 11 Nov 2026) on 28 November 2026. Each section links to the official docs it was checked against.

This sheet is for people on shared hosting, a CMS or any Apache box where .htaccess is the only config file you are allowed to touch. Everything here was checked against the Apache httpd 2.4 documentation on the day 2.4.71 was the current release. We could not run Apache in our sandbox, so every row is marked as checked in the docs rather than tested.

When to use what

Start with the question Apache's own docs ask: do you have access to the main server config? If you do, put the rules there. A .htaccess file is read on every request, and httpd also has to look for one in every parent directory, so a request for /www/htdocs/example/page.html costs four extra file-system checks even when none of those files exist.

If you are stuck with .htaccess, pick the smallest tool for the job. A plain move from one path to another is a Redirect. A pattern of old URLs is a RedirectMatch. Reach for RewriteRule only when you need a condition (host name, HTTPS, file exists) or an internal rewrite the visitor never sees, such as sending every unknown path to index.php. Mixing the two in one file is legal but confusing: in .htaccess the mod_alias directives run first, while in a virtual host mod_rewrite runs first.

Our .htaccess generator writes the common blocks for you, and if you are moving to Nginx the .htaccess to Nginx converter translates them. The Apache redirects post walks through Redirect, RedirectMatch and mod_rewrite side by side.

These lines go in the main server config, not in .htaccess itself. The default is AllowOverride None, so a brand-new Apache install ignores your file completely and you get no error, just no effect.

AllowOverride None

Default. Apache never even looks for .htaccess files in this directory tree

From the docs, not run by us
AllowOverride FileInfo

Lets .htaccess use Redirect, RedirectMatch, RewriteRule and Header, which all need the FileInfo class

From the docs, not run by us
AllowOverride FileInfo Indexes

Also allow ExpiresByType and ExpiresDefault, which are in the Indexes class, not FileInfo

From the docs, not run by us
AllowOverrideList Redirect RedirectMatch RewriteEngine RewriteRule RewriteCond

Allow only these named directives; any other directive in .htaccess becomes a 500 error

From the docs, not run by us
AccessFileName ".config"

Make Apache read per-directory settings from a file called .config instead of .htaccess

From the docs, not run by us

Redirect matches whole path segments and carries the rest of the path and the query string across. Its default status is 302, so write permanent when you mean a 301.

Redirect "/one" "/two"

Temporary 302 redirect; /one/page.html goes to /two/page.html with the query string kept

Try it: .htaccess GeneratorFrom the docs, not run by us
Redirect permanent "/docs" "https://docs.example.com/"

301 redirect of a whole path prefix to another host

From the docs, not run by us
Redirect seeother "/form" "/thanks"

Send a 303 See Other, the status for 'the result lives at another URL'

From the docs, not run by us
Redirect gone "/old-promo"

Answer 410 Gone with no target URL, for pages removed for good

From the docs, not run by us
RedirectMatch 301 "^/blog/(\d+)/(.+)$" "/posts/$2"

Regex redirect; captured groups are available as $1, $2 in the target

Try it: Regex TesterFrom the docs, not run by us

In .htaccess the directory prefix is stripped before matching, so the pattern never starts with a slash: ^/about$ silently never matches. Use %{REQUEST_URI} in a RewriteCond if you need the full path. The engine also needs FollowSymLinks or SymLinksIfOwnerMatch enabled for that directory.

RewriteEngine On

Switch on mod_rewrite for this directory; without it every RewriteRule below is ignored

From the docs, not run by us
RewriteRule "^about$" "about.php" [END]

Serve about.php for /about without changing the address bar

From the docs, not run by us
RewriteCond "%{REQUEST_FILENAME}" !-f

Only continue if the request does not map to an existing regular file

From the docs, not run by us
RewriteCond "%{REQUEST_FILENAME}" !-d

Only continue if the request does not map to an existing directory

From the docs, not run by us
RewriteCond "%{HTTP_HOST}" "^example\.com$" [NC]

Match the bare host name, case-insensitively, before a www redirect

From the docs, not run by us
RewriteCond "%{HTTP:X-Forwarded-Proto}" =http [NC]

Detect plain HTTP behind a load balancer, where %{HTTPS} always reads off

From the docs, not run by us
LogLevel alert rewrite:trace3

Log each rewrite step to the error log; server or directory config only, not .htaccess

Levels above trace2 slow the server noticeably; turn it off after debugging

From the docs, not run by us

Flags go in square brackets after the target and combine with commas, for example [R=301,L]. They are not case sensitive.

[R=301,L]

External 301 redirect and stop; plain [R] sends a 302

From the docs, not run by us
[END]

Stop rewriting and do not run the rules again on the new URL; the safe choice in .htaccess

From the docs, not run by us
[L]

Stop this pass; in .htaccess the rewritten URL is processed again from the top

From the docs, not run by us
[NC]

Make the pattern case-insensitive

From the docs, not run by us
[QSA]

Keep the visitor's query string and add it after the one in your target

From the docs, not run by us
[QSD]

Drop the incoming query string; wins over QSA if you set both

From the docs, not run by us
[NE]

Do not percent-encode the target, so # and ? in it survive as written

From the docs, not run by us
RewriteRule "\.exe$" "-" [F]

Return 403 Forbidden; '-' means leave the URL unchanged, and L is implied

From the docs, not run by us
RewriteRule "^oldproduct" "-" [G,NC]

Return 410 Gone for anything starting with oldproduct

From the docs, not run by us

Header writes to the onsuccess table by default, which only reaches 2xx responses. Add always for headers that must also appear on redirects and error pages, and for headers set by PHP or other CGI backends, which live in the always table. Expiry rules come from mod_expires (https://httpd.apache.org/docs/2.4/mod/mod_expires.html), which sets both Expires and Cache-Control: max-age.

Header set X-Content-Type-Options "nosniff"

Add or replace a response header on successful responses

Try it: http-header-generatorFrom the docs, not run by us
Header always set X-Content-Type-Options "nosniff"

Same header, but also on 3xx, 4xx and 5xx responses

Try it: Security Headers AnalyzerFrom the docs, not run by us
Header always unset X-Powered-By

Remove a header added by PHP or a CGI script, which only the always table can see

From the docs, not run by us
Header append Cache-Control s-maxage=600 "expr=%{REQUEST_STATUS} == 200"

Add a shared-cache lifetime only when the status is 200

Try it: Cache-Control BuilderFrom the docs, not run by us
ExpiresActive On

Turn on mod_expires so the ExpiresByType lines take effect

From the docs, not run by us
ExpiresByType image/png "access plus 1 month"

Cache PNGs for a month from the time of each request

From the docs, not run by us

Order, Allow and Deny come from mod_access_compat and are deprecated. Old tutorials still show them; translate them to Require when you touch the file.

Require all denied

Block every request to this directory

From the docs, not run by us
Require ip 192.168.1.0/24

Allow only one subnet; partial forms like 172.20 and netmask forms also work

Try it: CIDR CalculatorFrom the docs, not run by us
Require not ip 10.252.46.165

Exclude one address; must sit inside a RequireAll with a granting line

From the docs, not run by us
<RequireAll> Require all granted Require not ip 10.252.46.165 </RequireAll>

Everyone except one address, the documented way to block a single client

From the docs, not run by us
<Files ".env"> Require all denied </Files>

Refuse to serve one file by name; <Files> is allowed in .htaccess

From the docs, not run by us

Worked example: Front controller plus HTTPS and www, in one .htaccess

A typical PHP app on shared hosting needs three things: force HTTPS, force one host name, and send every path that is not a real file to index.php. With no access to the virtual host, it all goes in the document root's .htaccess:

RewriteEngine On

# 1. HTTP to HTTPS (behind a proxy, test %{HTTP:X-Forwarded-Proto} instead)
RewriteCond "%{HTTPS}" !=on
RewriteRule "^(.*)$" "https://www.example.com/$1" [R=301,L]

# 2. Bare domain to www
RewriteCond "%{HTTP_HOST}" "^example\.com$" [NC]
RewriteRule "^(.*)$" "https://www.example.com/$1" [R=301,L]

# 3. Everything that isn't a file or directory goes to the app
RewriteCond "%{REQUEST_FILENAME}" !-f
RewriteCond "%{REQUEST_FILENAME}" !-d
RewriteRule "^(.*)$" "/index.php" [END]

Then check it from your machine:

curl -sI http://example.com/pricing?plan=pro
curl -sI https://www.example.com/pricing

We could not run Apache here, so this is what the docs say you should see rather than captured output. The first request should come back as a single 301 with Location: https://www.example.com/pricing?plan=pro: the query string is carried over because the target has no ? of its own. If you see two hops (HTTP to HTTPS, then to www), your rules are in the wrong order or the first rule writes %{HTTP_HOST} instead of the canonical name. The second request should be a 200 served by index.php. Note that $1 has no leading slash in .htaccess, which is why the target writes the slash itself. If you get a 500 instead, the host probably has AllowOverride set too low for mod_rewrite; the error log names the directive it refused. Paste the response headers into our HTTP header parser if you want them laid out.

Common mistakes

  • Writing RewriteRule ^/old$ /new in .htaccess and wondering why nothing happens.

    Drop the leading slash: in per-directory context the pattern is matched against old, not /old. Use ^old$.

  • Using [L] on a catch-all rule in .htaccess and getting a 500 error from a rewrite loop.

    Use [END], or add a RewriteCond that skips requests already pointing at the target file, so the second pass doesn't match again.

  • Shipping Redirect /old /new and expecting search engines to treat it as a permanent move.

    Redirect defaults to 302. Write Redirect permanent or Redirect 301 when the move is final.

  • Testing %{HTTPS} behind Cloudflare or a load balancer, which causes an endless redirect loop.

    TLS ends at the proxy, so Apache always sees off. Test %{HTTP:X-Forwarded-Proto} instead, and only trust it if the proxy overwrites that header on every request.

  • Adding security headers with plain Header set and finding them missing on redirects and error pages.

    Use Header always set for headers that must be on every response, then check a 404 page with our security headers analyzer.

  • Copying Order deny,allow blocks from an old tutorial into an Apache 2.4 site.

    Rewrite them with Require. The old directives only work through mod_access_compat, which is deprecated and may not be loaded.