.htaccess cheat sheet

This cheat sheet brings together common .htaccess settings, from 301 redirects and HTTPS, through URL rewriting, access blocking, and password protection, to caching, compression, and security headers. You can search for a setting, filter by topic, and copy it with one click.

Redirects

  • Redirect 301 /old-page.html /new-page.html

    A permanent (301) redirect from one page to another on the same website, for a page that has moved to a new URL for good. The first path starts with a slash and is case-sensitive. The Redirect and RedirectMatch directives require the mod_alias module.

  • Redirect 301 /old-folder https://www.example.com/new-folder

    Redirects an entire folder. The match is on the beginning of the path, and anything after it is appended to the target URL, so /old-folder/page.html redirects to /new-folder/page.html. Parameters after the question mark are kept as well.

  • RedirectMatch 301 ^/blog/(.*)$ https://blog.example.com/$1

    A redirect based on a regular expression. The part in parentheses is captured in $1 and inserted into the target URL, for example to move all blog posts to a subdomain.

  • Redirect 301 / https://www.example-new.com/

    Moving to a new domain: place this line in the old domain's file, and every URL redirects to the same path on the new domain. When both domains point to the same folder, this line creates a redirect loop, so use the next rule instead.

  • RewriteEngine On RewriteCond %{HTTP_HOST} ^(www\.)?old-example\.com$ [NC] RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]

    Moving to a new domain when the old and new domains point to the same folder. The condition checks the domain name in the request, so only requests for the old domain are redirected, with the full path.

  • Redirect 302 /sale /summer-sale

    A temporary (302) redirect, for a page that will return to its original URL. Without a status code, the Redirect directive sends a temporary redirect by default, so state 301 explicitly for a permanent redirect.

  • Redirect 410 /discontinued.html

    Returns a 410 (Gone) status, which marks the page as permanently removed with no replacement. A status code that is not a redirect takes no target URL.

HTTPS and www

  • RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

    Redirects all HTTP traffic to the same URL over HTTPS, including the path and parameters. Before you enable it, make sure an SSL certificate is installed and active on the domain. RewriteRule and RewriteCond rules require the mod_rewrite module.

  • RewriteEngine On RewriteCond %{HTTP:X-Forwarded-Proto} =http [NC] RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

    A version for a website behind a proxy, load balancer, or CDN that receives the encrypted connection. In that setup, the server sees a plain connection even when the visitor browses over HTTPS, and the previous rule creates a redirect loop. Use this rule only when the proxy sets the X-Forwarded-Proto header on every request.

  • RewriteEngine On RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]

    Redirects from the www address to the address without www. The %1 variable returns the domain name captured in the condition, so the rule works for any domain without changes.

  • RewriteEngine On RewriteCond %{HTTP_HOST} ^example\.com$ [NC] RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]

    Redirects from the address without www to the address with www. The condition includes the exact domain name, so subdomains such as shop.example.com are not redirected by mistake.

  • RewriteEngine On RewriteCond %{HTTPS} !=on [OR] RewriteCond %{HTTP_HOST} ^www\. [NC] RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L]

    Moves to HTTPS and to the address without www in a single redirect, instead of two redirects in a row. The [OR] flag joins the two conditions, so it is enough for one of them to match.

URL rewriting

  • RewriteEngine On

    Turns on the rewrite engine and is written once, before the rules. In a .htaccess file, the FollowSymLinks or SymLinksIfOwnerMatch option is also required, and FollowSymLinks is enabled by default.

  • RewriteRule ^about$ about.php [L]

    An internal rewrite: the visitor sees the URL /about, and the server serves the about.php file. In a .htaccess file, the path is matched without its leading slash, so the pattern starts with ^about and not ^/about.

  • RewriteRule ^product/([0-9]+)$ product.php?id=$1 [L,QSA]

    Maps a friendly URL such as /product/25 to a URL with a parameter. The QSA flag keeps any additional parameters that came with the request; without it, they are dropped when the target URL contains a question mark.

  • RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^(.+)$ $1.php [L]

    Lets visitors browse to /contact and get the contact.php file, provided that such a file exists. This keeps the .php extension out of the website's URLs.

  • RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^ index.php [L]

    Sends every URL that is not an existing file or folder to index.php, the approach many content management systems and frameworks use. The !-f and !-d conditions make sure that images, CSS files, and other existing files are served as usual.

  • FallbackResource /index.php

    A simpler alternative to the previous rule, from the mod_dir module: every URL that does not exist on the server is passed to index.php, and existing files are served as usual, without the rewrite engine. LiteSpeed servers do not support this directive, so use the previous rule on them.

  • RewriteBase /blog/

    Sets the path that is added to relative target URLs. It is needed mainly when the file is in a subfolder, for example on a website installed in the /blog folder.

  • RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [R=301,L]

    Removes the trailing slash from URLs with a permanent redirect, for example from /about/ to /about. The first condition excludes real folders, to which the server adds a slash on its own.

  • RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_URI} !/$ RewriteRule ^ %{REQUEST_URI}/ [R=301,L]

    Adds a trailing slash to URLs that are not files, for example from /about to /about/. Choose one form for the whole website, and do not enable this rule together with the rule that removes the slash.

Flags and variables

  • [L]

    Stops processing rules in the current round. In a .htaccess file, the resulting URL may go through the rules again, so a faulty rule can create a loop.

  • [END]

    Stops all rewrite processing, including the extra round that runs in a .htaccess file. Useful for preventing loops in internal rewrite rules.

  • [R=301,L]

    A permanent external redirect, after which no further rules are processed. The R flag without a code sends a temporary (302) redirect, so state 301 for a permanent redirect.

  • [NC]

    Case-insensitive matching, for example jpg and JPG. It also works in RewriteCond conditions.

  • [QSA]

    Appends the original URL parameters to the parameters in the target URL instead of replacing them.

  • [QSD]

    Discards the original parameters from the URL, for example when redirecting to a clean URL without parameters.

  • [NE]

    Prevents special characters such as # from being encoded in the redirect URL. It is needed, for example, when redirecting to an anchor within a page.

  • RewriteRule ^private/ - [F]

    The F flag returns a 403 (Forbidden) status and stops processing. The hyphen in place of the target URL means that the URL is not changed. The G flag returns a 410 (Gone) status in the same way.

  • [OR]

    Joins a RewriteCond condition to the next one with a logical "or". Without the flag, all the conditions before the rule must match.

  • $1 %1

    $1 returns the part captured in parentheses in the RewriteRule pattern, and %1 returns the part captured in the last matching RewriteCond condition.

  • %{HTTP_HOST} %{REQUEST_URI} %{QUERY_STRING}

    Common variables in conditions: the domain name in the request, the path without parameters, and the parameters after the question mark.

Access blocking

  • Require all denied

    Blocks browser access to the folder that contains the file and to every folder below it. Suitable for folders of backups, logs, or internal files that nobody should browse to.

  • <Files ".env"> Require all denied </Files>

    Blocks access to a specific file, for example a .env file that holds passwords and access keys. You can block another file, such as wp-config.php, the same way.

  • <FilesMatch "\.(?i:bak|sql|log|ini|sh)$"> Require all denied </FilesMatch>

    Blocks files by extension, such as backups, database files, and logs left in the website folder. The ?i: prefix ignores the difference between uppercase and lowercase letters.

  • RewriteEngine On RewriteRule "(^|/)\.(?!well-known/)" - [F]

    Blocks access to every file and folder whose name starts with a dot, such as .git and .env, and returns a 403 status. The .well-known folder is excluded because it is used to validate SSL certificates and other services.

  • Require ip 203.0.113.10

    Allows access only from a specific IP address, for example in the .htaccess file of an admin folder. You can list several addresses and ranges on the same line, such as 203.0.113.0/24.

  • <RequireAll> Require all granted Require not ip 198.51.100.7 192.0.2.0/24 </RequireAll>

    Blocks an IP address or range and allows access to everyone else. The Require not directive does not grant access on its own, so it goes inside RequireAll together with Require all granted. When the website runs behind a proxy or CDN, the server sees their address and not the visitor's address.

  • <Files "wp-login.php"> Require ip 203.0.113.10 </Files>

    Restricts the WordPress login page to a fixed IP address, an effective defense against password guessing attempts. Suitable only when the IP addresses of the website's admins do not change.

  • RewriteEngine On RewriteCond %{HTTP_USER_AGENT} (BadBot|EvilScraper) [NC] RewriteRule ^ - [F]

    Blocks bots by the User-Agent string they send and returns a 403 status. The client sends this string and it is easy to fake, so the block stops only simple bots.

  • RewriteEngine On RewriteCond %{HTTP_REFERER} !^$ RewriteCond %{HTTP_REFERER} !^https?://(www\.)?example\.com/ [NC] RewriteRule \.(?:jpe?g|png|gif|webp)$ - [F,NC]

    Prevents other websites from displaying images stored on your website (hotlinking) and adding load to the server. Requests without a Referer are allowed, because many browsers and programs do not send it.

Password protection

  • htpasswd -B -c /home/example/.htpasswd admin

    A command for the command line, not a line in the .htaccess file. It creates a password file with a first user and hashes the password with bcrypt. Caution: the -c option overwrites an existing file at the same path. Keep the file outside the website's public folder.

  • htpasswd -B /home/example/.htpasswd editor

    Adds a user to an existing file or changes the password of an existing user. Without the -c option, the file keeps all of its users.

  • htpasswd -D /home/example/.htpasswd editor

    Deletes a user from the password file.

  • AuthType Basic AuthName "Restricted area" AuthUserFile /home/example/.htpasswd Require valid-user

    Protects the folder with a username and password. The AuthUserFile directive takes a full path on the server, not a website URL. With the Basic method, the password is sent without encryption of its own, so use it only on a website that runs over HTTPS.

  • <Files "admin.php"> AuthType Basic AuthName "Restricted area" AuthUserFile /home/example/.htpasswd Require valid-user </Files>

    Password-protects a single file, for example an admin page, while the rest of the website stays open to visitors.

Error pages

  • ErrorDocument 404 /404.html

    Shows a custom page when a page is not found. The path starts with a slash and is relative to the website's root folder, and the visitor still gets the original 404 status.

  • ErrorDocument 403 /errors/403.html

    A custom page for blocked access (403). You can set a page for the 500 error and other codes the same way.

  • ErrorDocument 403 "Access denied"

    A short text message instead of a full page. Text that contains spaces goes in quotation marks.

  • ErrorDocument 404 https://www.example.com/not-found

    Not recommended: a full URL makes the server send a redirect instead of a 404 status, so visitors and search engines do not get the original error code. A local path is better, and for the 401 error a local path is required.

Caching and compression

  • <IfModule mod_expires.c> ExpiresActive On ExpiresByType image/webp "access plus 1 month" ExpiresByType image/jpeg "access plus 1 month" ExpiresByType image/png "access plus 1 month" ExpiresByType text/css "access plus 1 week" ExpiresByType text/javascript "access plus 1 week" ExpiresByType application/javascript "access plus 1 week" </IfModule>

    Keeps images, CSS, and JavaScript files in the browser cache for the period you set, so repeat visits load faster. The mod_expires module sends the Expires and Cache-Control headers, and the IfModule condition prevents an error when the module is not enabled.

  • <FilesMatch "\.(?i:css|js|woff2)$"> Header set Cache-Control "max-age=31536000, immutable" </FilesMatch>

    Caching for a full year, for files whose name changes with every update, for example style.3f9a2c.css. For files whose name stays the same, visitors may see an old version until the period ends. The Header directive requires the mod_headers module.

  • <FilesMatch "\.(?i:html?)$"> Header set Cache-Control "no-cache" </FilesMatch>

    The browser may store the page, but it must check with the server that the page is up to date before each display. The no-cache value does not forbid caching; to forbid it completely, use the no-store value.

  • <IfModule mod_deflate.c> AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/json image/svg+xml </IfModule>

    Compresses text files before they are sent to the browser (gzip), which reduces the transfer size and speeds up page loading. Images such as JPEG, PNG, and WebP are already compressed, so there is no need to add them to the list.

Security headers

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

    Stops the browser from guessing the file type. Script and style files sent with the wrong content type are blocked, which reduces attacks based on files uploaded to the website.

  • Header always set Referrer-Policy "strict-origin-when-cross-origin"

    Sets how much information about the current page is sent to another website when a visitor clicks a link: the full URL is sent only within the website, and other websites receive only the domain name. This is also the default in current browsers, and the setting makes it explicit.

  • Header always set X-Frame-Options "SAMEORIGIN"

    Prevents the website from being shown inside an iframe on other websites, a defense against clickjacking, which hides the website under misleading buttons on a third-party website. The DENY value also blocks display within the website itself. The header works only when the server sends it, not in a meta tag.

  • Header always set Content-Security-Policy "frame-ancestors 'self'"

    The modern, more flexible way to get the same protection, which also lets you list allowed websites, for example 'self' https://partner.example.com. If the website already sends a CSP policy, add frame-ancestors to the existing policy.

  • Header always set Strict-Transport-Security "max-age=31536000"

    Caution: tells the browser to access the website only over HTTPS for the period set in seconds, here one year. While that period is in effect, an SSL certificate problem blocks access to the website with no way to bypass the warning. Start with a small value, and add includeSubDomains only when all subdomains run over HTTPS.

  • Header always unset X-Powered-By Header unset X-Powered-By

    Removes the X-Powered-By header, which some applications add with the name and version of their technology. Both lines are needed because the header may come from two different sources on the server.

  • ServerSignature Off

    Removes the signature line with the server name and version from the bottom of error pages and folder listings that the server generates. This is the default, and the setting is useful when the signature was enabled in the main configuration.

CORS and fonts

  • <FilesMatch "\.(?i:woff2?|ttf|otf)$"> Header set Access-Control-Allow-Origin "*" </FilesMatch>

    Lets other websites and subdomains load the website's fonts. Without this header, browsers block loading a font from another domain, for example when the fonts are served from a subdomain or a CDN.

  • Header set Access-Control-Allow-Origin "https://app.example.com" Header merge Vary Origin

    Allows access from one domain only instead of any domain. The header accepts a single domain, and the Vary: Origin header prevents an intermediate cache from serving a response meant for another domain. The * value is not suitable for requests that include cookies or login credentials.

Folders and file types

  • Options -Indexes

    Turns off the file listing in folders that have no index page, so visitors cannot browse the contents of your folders. In a .htaccess file, write the option with + or -, otherwise it replaces all the options set on the server.

  • Options -MultiViews

    Turns off MultiViews, which serves a file with a similar name, such as about.php for a request to /about, and can conflict with rewrite rules.

  • DirectoryIndex index.php index.html

    Sets the file shown when a visitor opens a folder. The server looks for the files in order and shows the first one that exists.

  • AddType image/avif .avif

    Sets the content type (MIME) for an extension, when the server sends a wrong or generic type for newer file types. More examples: AddType image/webp .webp and AddType font/woff2 .woff2.

  • AddDefaultCharset UTF-8

    Adds the UTF-8 character encoding to the content type header of HTML pages and text files, and prevents non-Latin text from appearing as garbled characters in static files.

  • <FilesMatch "\.(?i:pdf|zip)$"> Header set Content-Disposition "attachment" </FilesMatch>

    Makes the browser download the file instead of opening it. You can also suggest a name for the saved file with the value attachment; filename="file.pdf".

A .htaccess file is a configuration file placed in a website folder, and its settings apply to that folder and to every folder below it. The file is supported by Apache-compatible web servers, while Nginx does not read it, and the equivalent settings go in its configuration files. The domain names, file paths, and IP addresses on this page are examples, so replace them with your real values.

Each group of settings requires a matching server module: Redirect directives require mod_alias, rewrite rules require mod_rewrite, headers require mod_headers, caching with the Expires directives requires mod_expires, and compression requires mod_deflate. In Apache, a setting the server does not recognize, or one that is not allowed in a .htaccess file, causes a 500 error across the whole website. Before any change, save a copy of the file, and after the change, check the website and the error log.

Content management systems such as WordPress write their own rules to the file between the # BEGIN WordPress and # END WordPress lines, and changes inside that section may be overwritten by an update. It is best to add your own rules, especially redirects, above that section.

You can create redirect rules with the .htaccess redirect generator, check the redirects of a URL with the redirect checker, and check the headers a website sends with the HTTP header analyzer. You can create a line for a .htpasswd file without the command line in the bcrypt and htpasswd generator.

Web server compatibility

The settings on this page are written in Apache syntax, and support for them varies from server to server:

  • Apache: supports all the settings on this page, provided that the matching module is enabled and the server's AllowOverride setting allows them. The file is read on every request, so a change takes effect without restarting the server.
  • LiteSpeed Enterprise: is designed as a drop-in replacement for Apache and reads .htaccess files in the same syntax, and a change to the file does not require a restart. According to its documentation, the FallbackResource directive and MultiViews are not supported, so use a rewrite rule instead of FallbackResource. The [L] flag works in it like the [END] flag in Apache.
  • OpenLiteSpeed: reads only rewrite rules from .htaccess files, when loading the file is enabled in the server settings. Other directives, such as Redirect directives, Require access rules, password protection, headers, and caching, are not applied, and the equivalent settings are configured in the server's admin console. A change to the file takes effect after the server restarts, and some control panels restart it automatically after the file is edited.
  • Nginx: does not read .htaccess files, and the equivalent settings go in the server's configuration files.

A directive that the server does not support may not work at all, so after moving between servers, check that redirects, access blocks, and password protection work as expected. On some servers, PHP settings such as the maximum upload size are set in a .user.ini file or in the control panel, not in the .htaccess file.

Did you know?

With Linux hosting and WordPress hosting plans, you can edit the .htaccess file directly from the file manager in the control panel and set up redirects and custom error pages.

Linux hosting plans

.htaccess FAQ

What is a .htaccess file, and what can you do with it?

A .htaccess file is a configuration file in a website folder that lets you change how the server behaves without access to the main configuration. You can use it to set up 301 redirects, a permanent move to HTTPS, friendly URLs, access blocking for files and folders, password protection, custom error pages, caching, and security headers. The settings apply to the folder that contains the file and to every folder below it.

How do I set up a 301 redirect in a .htaccess file?

For a single page, one line is enough, for example Redirect 301 /old-page.html /new-page.html. To move an entire folder, write the folder path, and anything after it is appended to the target URL. For pattern-based redirects, use RedirectMatch or RewriteRule rules. Without the 301 code, a temporary (302) redirect is sent, so state it explicitly for a permanent redirect.

How do I move my whole website to HTTPS?

Once an SSL certificate is installed and active on the domain, add the RewriteEngine On line at the top of the file, a condition that checks whether the connection is unencrypted, and a rule that sends a 301 redirect to the same URL over HTTPS. This cheat sheet includes the full rule, as well as a version that combines the move to HTTPS with your preferred address, with or without www, in a single redirect.

Can a .htaccess file make my website faster?

Yes, when you use it to set up browser caching and compression. Expires and Cache-Control settings keep images, CSS, and JavaScript files in the visitor's browser, so repeat visits load faster, and compressing text files reduces the transfer size. Servers such as Apache read the file on every request, so it is best to keep only the settings you need in it.

Why does a 500 error appear after a change to the .htaccess file?

A 500 error right after a change usually points to a typo in a setting, a directive the server does not recognize, or a directive that is not allowed in a .htaccess file. The quickest fix is to restore the previous copy of the file, then add your changes gradually and check the website after each one. The website's error log usually names the directive that caused the error.

Shopping cart

Your cart is emptyYou can start with one of our popular plans.

Site search

Accessibility

Text size
100%
Accessibility statement