glunty

Apache htaccess Cheat Sheet

A searchable reference of common Apache htaccess directives and what each one does.

Common Apache htaccess directives with a plain-English description of what each one does
Directive What it does
RewriteEngine On Turn on the mod_rewrite engine so rewrite rules in this file take effect.
RewriteBase / Set the base path that relative RewriteRule substitutions are resolved against.
RewriteRule ^pattern$ /target [L] Rewrite a request whose path matches the regex to a new target, then stop.
RewriteRule ^blog/(.*)$ /articles/$1 [L] Capture part of the URL with a group and reuse it as $1 in the target.
RewriteCond %{HTTP_HOST} ^example\.com$ [NC] Add a test that must pass before the RewriteRule directly below it runs.
[L] Last flag: stop processing further rewrite rules when this rule matches.
[R=301] Redirect flag: send an external 301 permanent redirect to the substitution URL.
[QSA] Query string append flag: keep the original query string on the rewritten URL.
[NC] No case flag: match the pattern regardless of upper or lower case.
[F] Forbidden flag: return a 403 response and stop instead of rewriting.
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] Force HTTPS by redirecting to the secure URL (pair with RewriteCond %{HTTPS} off above it).
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L] Force www by redirecting the bare domain to the www host (pair with a RewriteCond on the host).
RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L] Remove www by redirecting www requests to the bare domain (pair with a RewriteCond on the host).
RewriteRule ^(.*)/$ /$1 [R=301,L] Remove a trailing slash by redirecting to the same path without it.
RewriteRule ^products/([0-9]+)$ product.php?id=$1 [L] Pretty URLs: map a clean path to a script with query parameters internally.
Redirect 301 /old-page /new-page Permanently redirect one path to another with mod_alias, no mod_rewrite needed.
Redirect 301 /old.html https://example.com/new Redirect a single page to a full URL on any host.
Redirect 302 /promo /new-promo Temporarily redirect a path with a 302 so clients do not cache the move.
RedirectMatch 301 ^/blog/(.*)$ /news/$1 Redirect every URL matching a regex, reusing the captured group in the target.
Redirect permanent /a /b Same as Redirect 301, written with the named status permanent.
RewriteRule ^(.*)$ https://newsite.com/$1 [R=301,L] Redirect an entire domain to a new one while keeping the requested path.
Require all granted Grant every client access to this directory (Apache 2.4 authorization syntax).
Require all denied Block all clients from this directory.
Require ip 203.0.113.5 Allow access only from a specific IP address or CIDR range.
<Files "wp-config.php"> Open a block whose directives apply only to the named file (add Require all denied inside).
<FilesMatch "\.(env|log|ini)$"> Apply access rules to every file whose name matches the regex, such as secrets.
AuthType Basic Start HTTP Basic authentication for a protected directory.
AuthName "Restricted Area" Set the realm text shown in the browser login prompt.
AuthUserFile /home/user/.htpasswd Point Basic auth at the password file created with the htpasswd tool.
Require valid-user Require any authenticated user from the password file to gain access.
RewriteCond %{HTTP_USER_AGENT} "^BadBot" [NC] Match a user agent so the next rule can block it (pair with RewriteRule ^ - [F]).
ErrorDocument 404 /404.html Serve a custom page when a requested URL is not found.
ErrorDocument 500 /500.html Serve a custom page for internal server errors.
ErrorDocument 403 /forbidden.html Serve a custom page for forbidden requests.
ExpiresActive On Turn on mod_expires so Expires and Cache-Control headers are generated.
ExpiresByType image/png "access plus 1 year" Tell browsers to cache a given content type for a set time.
Header set Cache-Control "max-age=2592000" Set an explicit Cache-Control header with mod_headers.
AddOutputFilterByType DEFLATE text/html text/css application/javascript Gzip-compress matching text responses with mod_deflate.
Header set X-Frame-Options "SAMEORIGIN" Stop other sites from framing your pages to reduce clickjacking.
Header set X-Content-Type-Options "nosniff" Stop browsers from MIME-sniffing responses away from the declared type.
Options -Indexes Disable directory listing so visitors cannot browse folder contents.
Options +FollowSymLinks Allow the server to follow symbolic links, which mod_rewrite often needs.
DirectoryIndex index.html index.php Set which file is served when a directory URL is requested.
AddType image/webp .webp Map a file extension to the MIME type the server sends for it.
AddType application/manifest+json .webmanifest Register a custom MIME type for an uncommon file extension.
AddHandler application/x-httpd-php74 .php Tell Apache which handler processes files with a given extension.
php_value upload_max_filesize 64M Change a PHP setting when PHP runs as an Apache module.
RewriteCond %{HTTP_REFERER} !^https://(www\.)?example\.com [NC] Hotlink protection: block other sites from embedding your images (pair with a RewriteRule on image files).
AddDefaultCharset UTF-8 Set the default character set the server declares for text responses.

Runs entirely in your browser. Nothing you type is sent anywhere; open DevTools and watch the Network tab to verify zero requests.

What this tool does

This is a searchable quick reference for the Apache htaccess directives you reach for most often, from rewriting and redirecting URLs to controlling access, serving custom error pages, and tuning caching and compression. Each row pairs the directive with a plain-English note on what it does, accurate to Apache 2.4. Type in the filter box to search across both columns, or tap a category button to focus on one area. The whole list is built into the page, so it works offline and sends nothing anywhere.

How to use it

Start typing in the Filter box. Entering https surfaces the force-HTTPS rewrite; entering 301 shows the permanent redirects; entering cache brings up the caching and header directives. The category buttons (Rewrite, Redirect, Access, Errors and perf, Misc) narrow the table to one family and combine with the text filter, so you can pick Rewrite and type flag to see just the rewrite flags. Clear the box to see the full sheet again.

Common use cases

  • Recalling the exact rewrite recipe to force HTTPS or add or remove the www prefix.
  • Copying a safe Redirect 301 line instead of guessing the mod_alias syntax.
  • Locking down a folder with HTTP Basic auth or denying access to a config file.
  • Setting cache lifetimes and gzip so a static site scores better on speed tests.
  • Disabling directory listing with Options -Indexes before a site goes live.

Common pitfalls

  • Forgetting RewriteEngine On. Rewrite rules are silently ignored until the engine is enabled, so put RewriteEngine On before any RewriteRule in the file.
  • Redirect loops on HTTPS. A force-HTTPS rule with no RewriteCond %{HTTPS} off guard keeps matching after the redirect and loops. Always gate the rule on a condition.
  • Order-of-operations surprises. Apache reads directives top to bottom, and an early [L] stops the rest. Put broad redirects near the top and more specific rewrites where they will actually be reached.
  • Mixing old and new access syntax. Apache 2.4 uses Require all denied and Require all granted, not the old Order, Allow, and Deny directives, which need mod_access_compat to keep working.

Frequently asked questions

What is an htaccess file?
An .htaccess file is a per-directory configuration file for the Apache web server. When Apache is set to allow it, the server reads the .htaccess file in a folder on every request and applies its directives to that folder and everything below it, with no restart needed. It is commonly used for redirects, URL rewriting, access control, and caching headers on shared hosting where you cannot edit the main server config.
How do I redirect HTTP to HTTPS in htaccess?
Enable mod_rewrite with RewriteEngine On, then add RewriteCond %{HTTPS} off followed by RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]. The condition limits the rewrite to plain HTTP requests, and the rule sends a permanent 301 redirect to the same URL over HTTPS. Place it near the top of your .htaccess so it runs before other rules.
What does RewriteCond do?
RewriteCond sets a condition that must be true for the RewriteRule immediately after it to run. It tests a server variable, such as %{HTTPS}, %{HTTP_HOST}, or %{HTTP_USER_AGENT}, against a pattern. You can stack several RewriteCond lines, which are combined with a logical AND by default, so the following rule fires only when every condition matches.
What do the rewrite flags mean?
Flags in square brackets change how a RewriteRule behaves. L stops further rule processing, R=301 turns the rewrite into an external permanent redirect, QSA appends the original query string, NC makes the match ignore case, and F returns a 403 Forbidden response. You can combine them with commas, for example [R=301,L].
How do I password protect a directory with htaccess?
Create a password file with the htpasswd tool, then in the folder .htaccess add AuthType Basic, AuthName with a realm label, AuthUserFile pointing at that password file, and Require valid-user. Apache then prompts visitors for a username and password using HTTP Basic authentication before serving anything in that directory. Always serve it over HTTPS so the credentials are not sent in the clear.
Does this cheat sheet send my searches anywhere?
No. The full directive list is built into the page and every filter and search runs locally in your browser with JavaScript, so nothing you type leaves your device. Open your browser DevTools and watch the Network tab while you search to confirm there are zero requests.

Embed this tool

Free for any use; attribution appreciated. Paste this on your site:

The embed runs the same tool that lives at this URL. No tracking; no ads inside the embed. Resize height as needed for your layout.

Cite this tool

For academic, journalistic, or technical references. Pick a format:

Citations use 2026 as the publication year. Access date is left as a fillable placeholder where the citation style expects one.

Embedded tool from glunty.com