On this page
This guide is a complete reference for the .htaccess file: from understanding how it works internally and why it costs performance, to every practical use you will actually need, with copy-ready code explained line by line, and finally a real troubleshooting section that tackles the three situations that trip everyone up: the 500 error, the infinite redirect loop, and the file that "doesn't work at all." Read it through once to build the right mental model, then come back to it as a reference to copy the rule you need.
What exactly is the .htaccess file and how does it work?
The file's name is short for hypertext access. It was originally designed to let a site owner on a shared server control access behavior for their directory without having permission to edit the server's main configuration. This original idea is the key to understanding the whole file: it is decentralized, distributed configuration that gives you limited authority over your own directory only, while the main configuration file (httpd.conf or the vhost files) remains exclusive to the server administrator.
In practice it is an ordinary text file — no extension and no special format — in which you write directives that Apache understands, one line at a time. No programming language, no variables or loops, just direct declarative commands such as: "redirect this path to that one," "deny access to this file," "add this header to the response." This simplicity is the source of both its power and its danger: one line can switch your entire site from HTTP to HTTPS, and another, wrong line can bring it down entirely.
Why does the name start with a dot, and why can't you see it?
In Unix and Linux systems — the environment the overwhelming majority of hosting servers run on — any file whose name starts with a dot is considered a hidden file and doesn't appear in default listings. This isn't a security feature but an organizational convention meant to keep configuration files out of the everyday user's sight. The practical result for you: you open the file manager in the control panel, go into the public_html directory, and don't see the file even though it is there — so you think it doesn't exist, create a new one over the existing one, and lose your old rules.
The solution is simple: enable the option to show hidden files. In the cPanel file manager, you will find it when you open the manager in the Settings window at the top right, with an option called Show Hidden Files (dotfiles). If you aren't familiar with the file manager and the panel's components in general, the cPanel guide for beginners explains its sections and where to start. In FileZilla, the option is in the Server > Force showing hidden files menu, and you will find the details of connecting and uploading in the guide to uploading files via FTP and FileZilla.
How does the server read the file on every request?
Many people overlook this point, and it is the essence of understanding the file's cost. When a visitor requests a page, Apache doesn't read just one .htaccess file; it walks the entire chain of directories from the site root down to the requested directory, looking in each one for an .htaccess file to read and merge its directives. This happens on every request — every page, every image, every CSS file — and it isn't kept in the server's memory like the main configuration.
The effect is twofold. The upside: any edit you write takes effect immediately without restarting the server, which is why it is so hugely popular on shared hosting. The downside: extra disk reads on every request, and repeated text parsing of the rules. On a site with modest traffic the difference is imperceptible, but on a site with thousands of requests per minute, or when the file fills up with hundreds of redirect rules, the cost starts to show as extra milliseconds in time to first byte (TTFB). The practical rule: if you are on a server where you have root, move fixed rules into the vhost configuration, where they are read once at startup, and keep .htaccess for cases where you need a quick edit.
Inheritance: one file per directory
There can be more than one .htaccess file on a single site, one in each directory. The file in a subdirectory inherits the directives of the file above it, and can add to them or override some of them. This inheritance is very useful: you put the general rules in the root file inside public_html, then put a narrow security rule inside wp-content/uploads, for example, that prevents PHP execution there alone, without affecting the rest of the site.
But inheritance is also a hidden source of confusion. If you write a rule in the root and it seems to "not work" in a particular directory, there is most likely another .htaccess file inside that directory overriding it. And some WordPress plugins and security tools silently create sub-.htaccess files in directories such as wp-content or wp-admin. Before you doubt your rule, search the whole directory tree for other .htaccess files.
| Directive | What it does | Required module |
|---|---|---|
Redirect / RedirectMatch | Redirects one path to another with a specific status code | mod_alias |
RewriteEngine / RewriteRule / RewriteCond | Rewrites URLs and redirects them based on conditions | mod_rewrite |
ErrorDocument | Sets a custom page for each error code | Core |
Options | Enables/disables directory features such as file listing | Core |
DirectoryIndex | Sets the order of default files opened when a directory is requested | mod_dir |
Require | Controls who is allowed access (IP, user, everyone) | mod_authz_core |
Header | Adds or modifies response headers | mod_headers |
AddOutputFilterByType | Compresses specific content types before sending them | mod_deflate |
ExpiresByType / ExpiresDefault | Sets the browser caching duration | mod_expires |
AuthType / AuthUserFile | Protects a directory with a password | mod_auth_basic |
php_value / php_flag | Changes PHP settings (works with mod_php only) | mod_php |
Where is the file, and how do you reach it?
The most important file lives in your published site root, i.e. inside public_html (or www or htdocs, depending on the host). This is the file that affects the whole site. If you have a subdomain or an addon domain, each one has its own root and its own file. The main account directory (Home) above public_html, however, isn't read at all because it is outside the publishing path.
| Access method | When it fits | Important note |
|---|---|---|
| The control panel's file manager | Quick editing, and the safest for beginners | Enable Show Hidden Files first |
| FTP/SFTP (FileZilla) | Local editing and uploading multiple copies | Enable showing hidden files from the Server menu |
SSH (nano .htaccess) | VPS servers and quick access without an interface | Requires terminal access |
| WordPress plugins | Editing from inside the dashboard | Risk: a syntax error can lock you out of the dashboard itself |
What if the file doesn't exist at all?
A missing file is completely normal, since it isn't required for the site to work. WordPress, for example, creates it automatically when you save the permalink settings if it has write permission, and if it doesn't, it shows you the block's content and asks you to paste it manually. To create the file from the file manager: click + File and type the name .htaccess with the dot at the beginning exactly, with no extension and no space. From the command line, a single command is enough.
Watch out for the Windows trap: File Explorer often refuses to create a file whose name starts with a dot, and some editors silently add a .txt extension, so the name becomes .htaccess.txt and the server doesn't read it at all. Write the file in a real text editor (VS Code or Notepad++), and save it with UTF-8 without BOM encoding and LF line endings, not CRLF. An invisible BOM mark at the start of the file is enough on its own to bring the site down with a 500 error for no apparent reason.
The correct file permissions
The right permission for the .htaccess file is 644 (read and write for the owner, read-only for everyone else). Don't set it to 777, no matter who advises you to in order to fix a permissions problem, because that means any process on the server can write to it — and a file that controls redirects and protection in an attacker's hands means a completely hijacked site. Some hardened servers refuse to read a file with 777 permissions and respond with a 500 error, which is actually protecting you.
Apache and LiteSpeed vs. Nginx — the point everyone gets wrong
This is the most common misconception in Arabic-language content about .htaccess, and hours are lost because of it: Nginx doesn't read the .htaccess file at all, and has no equivalent of any kind. It isn't a matter of a missing setting or a module you need to enable; it is a deliberate design decision in Nginx's architecture: all configuration is read once when the server starts and loaded into memory, and that is precisely part of what makes it fast. If it supported distributed files read on every request, it would lose that advantage.
So if you upload an .htaccess file to an Nginx server, nothing happens at all: no error, no warning and no effect. The file just sits there silently as an ordinary text file (it may even be downloadable from the browser if you don't block it). The correct alternative on Nginx is to write the directives inside the server block in the site's configuration file, then reload the service — which requires root access to the server, so it applies to VPS and dedicated servers, or must be requested from the server administrator or technical support on managed hosting.
LiteSpeed and OpenLiteSpeed, on the other hand, read .htaccess with very high Apache compatibility, which is a major reason they are so widespread on shared hosting: they deliver performance close to Nginx while keeping the flexibility of .htaccess in the customer's hands. For more on the architectural differences and which one suits your case, see the comparison between LiteSpeed and Nginx.
| Server | Reads .htaccess? | How rules are configured | Who can edit them |
|---|---|---|---|
| Apache | Yes, on every request | .htaccess or the vhost configuration | The customer |
| LiteSpeed / OpenLiteSpeed | Yes, with high compatibility | .htaccess or the server panel | The customer |
| Nginx | No, not at all | Directives inside the server block | The server administrator only |
| Nginx as a front end for Apache | Partly | The file works because Apache behind it does the processing | The customer, within limits |
| Caddy / IIS | No | Caddyfile / web.config | The server administrator |
The golden rule: a backup before any edit
This isn't routine advice repeated in every guide; it is a practical, non-negotiable requirement. The .htaccess file is one of the rare cases where a single typo is enough to bring the whole site down at that very moment, because the edit takes effect immediately and there is no "build" or "validation" stage to catch the error before it goes live. An extra letter in a directive name, an IfModule tag you didn't close, or a missing quote — and the result is a white page showing 500 Internal Server Error for every visitor, including you, and including the WordPress dashboard you would have used to fix it.
How to take a backup in thirty seconds
Before you touch the file, copy it under another name in the same directory: htaccess-backup-2026-07-28, for example. Notice that we deliberately removed the dot from the beginning of the name — this way the server stops treating it as a configuration file and it becomes just an inert text file. If things go wrong, delete the broken file, rename the copy back to .htaccess, and the site is back in seconds.
For the broader strategy that covers files and the database together, not just this file, see the website backup guide. And consider the manual copy above a complementary, on-the-spot measure, not a substitute for a regular automatic off-server backup.
Change one rule, then test
The approach that saves you hours of diagnosis is incremental editing: add one block, save, open the site in a private browsing window (to avoid the cache), and make sure it works. Then move on to the next. If you paste five blocks at once and the site goes down, you will spend time figuring out which one is responsible. And when testing, be sure to use a private window specifically, because the browser caches 301 redirects aggressively and may show you old behavior that makes you think your rule didn't work.
| Common mistake | What happens | Fix |
|---|---|---|
Forgetting to close </IfModule> | An immediate 500 error | Close every tag you open |
Writing RewriteRule without RewriteEngine On | The rule is silently ignored | Add RewriteEngine On once at the top of the block |
| Saving the file as UTF-8 with BOM | A 500 error for no apparent reason | Save as UTF-8 without BOM |
| Windows line endings (CRLF) | Strange behavior or a 500 error | Set the editor to LF |
The file is named .htaccess.txt | Nothing happens at all | Remove the hidden extension entirely |
A missing quote in Header set | A 500 error | Make sure every " is closed |
| A space inside an unquoted path | The rule doesn't match | Put the path in quotation marks |
| A general rule before a specific one | The specific rule never runs | Order from the narrowest to the most general |
File structure and rule order
The file is read from top to bottom, and the order really matters. The first rule that matches the request runs, and execution may stop there if it carries the [L] flag (short for Last). That is why you put the narrowest, most specific rules at the top and the broad, general rules at the bottom. If you reverse the order and put a general rule that matches everything at the beginning, the following rules will never get their turn.
Comments start with the # sign and take up the whole line. Use them generously: write a comment line for each block saying what it does and when you added it. Six months later, a file with twenty rules and no comments becomes a puzzle you won't dare touch.
# ————— My own rules (outside the WordPress block) —————
# 1) Disable directory listing
Options -Indexes
# 2) Set the default file when a directory is requested
DirectoryIndex index.php index.html
# 3) Default character set for text files
AddDefaultCharset UTF-8Line by line: Options -Indexes stops Apache from showing a list of files when it doesn't find a default file in the directory — without it, any visitor could browse the contents of wp-content/uploads or a backup directory and see what's inside. DirectoryIndex sets the order in which the server looks for the default file, trying index.php first and then index.html. And AddDefaultCharset UTF-8 ensures the server declares the correct character set in the response header, which prevents Arabic text from showing up as garbled characters on static pages.
301 and 302 redirects — the most common use
A redirect is when a visitor requests an address and the server replies: "this address is no longer here, go to that one." The difference between its codes isn't a technical detail but a decision with a direct impact on your site's indexing: the 301 code tells search engines the move is permanent, so they transfer the old page's value and backlinks to the new one and replace the address in the index. A 302, however, says "temporary," so search engines keep the old address in the index and transfer nothing. Using a 302 for a permanent move is one of the most common migration mistakes, and the result is lost rankings that could have been preserved entirely.
| Code | Meaning | Transfers ranking value? | When to use it |
|---|---|---|---|
| 301 | Permanent move | Yes | Changing a URL, merging two pages, moving a domain, standardizing HTTPS/www |
| 302 | Temporary move (changes the method to GET) | No | A page under maintenance, a seasonal offer, an A/B test |
| 307 | Temporary move (preserves the method) | No | Temporarily redirecting a POST request without breaking it |
| 308 | Permanent move (preserves the method) | Yes | Permanently moving an API that receives POST |
| 410 | Permanently deleted | No — it requests removal | Content deleted with no replacement that you don't want kept in the index |
| 404 | Not found | No | Not set manually here; it is the default response |
For a broader understanding of the other status codes and their meanings, see the HTTP status codes page in the wiki.
Method 1: the simple Redirect directive
# Redirect one page to another — permanent
Redirect 301 /old-page.html /new-page.html
# Redirect a page to an external site
Redirect 301 /partner https://example.com/landing
# Declare a page permanently deleted with no replacement
Redirect 410 /discontinued-productRedirect is the simplest tool and is enough for individual cases. The syntax: the keyword, then the status code, then the old path starting with a slash, then the destination. Notice that the 410 line takes no destination at all — the meaning is "deleted, no replacement," and adding a destination to it is a syntax error that takes the site down.
Method 2: RedirectMatch for patterns
# Move an entire directory while preserving the inner path
RedirectMatch 301 ^/blog/(.*)$ /articles/$1
# Standardize URLs ending in the .html extension
RedirectMatch 301 ^/(.*)\.html$ /$1Here we use regular expressions. The ^ symbol means the start of the path, (.*) captures everything after it, and $1 reuses what was captured in the destination. The first rule automatically turns /blog/my-post into /articles/my-post for all blog posts at once, instead of writing a line for each post. This rule alone saves you hundreds of lines when restructuring a site.
Method 3: RewriteRule when you need conditions
<IfModule mod_rewrite.c>
RewriteEngine On
# Redirect only visitors coming from a specific domain
RewriteCond %{HTTP_REFERER} old-domain\.com [NC]
RewriteRule ^(.*)$ https://example.com/welcome [R=301,L]
# Make a deleted page return 410 instead of 404
RewriteRule ^old-section/?$ - [G,L]
</IfModule>RewriteCond is a condition tested before the rule that immediately follows it, and the rule only runs if the condition is met. The flags in brackets: R=301 means "redirect with this code," L means "stop here and don't continue with the following rules," NC means "ignore letter case," and G means "respond with 410 Gone." The dash - in the destination position means "don't change the path, just apply the flag."
Forcing HTTPS and standardizing the www version
After installing an SSL certificate, your site becomes available at both addresses: http:// and https://. That isn't an acceptable state, because search engines treat them as two separate sites with duplicate content, link strength gets split between them, and visitors who open the unencrypted version remain exposed to having their data intercepted. The solution is to force the encrypted version at the server level. If you haven't installed the certificate yet, start with the guide to installing SSL and enabling HTTPS and then come back here.
<IfModule mod_rewrite.c>
RewriteEngine On
# 1) Force HTTPS on all requests
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# 2) Standardize the site on the non-www version
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
</IfModule>The first block: %{HTTPS} !=on means "if the connection isn't encrypted," so we rebuild the same address starting with https:// plus %{HTTP_HOST} (the domain as the visitor requested it) and %{REQUEST_URI} (the full path after the domain). The result: a visitor who opens http://example.com/blog/post goes straight to https://example.com/blog/post, not to the home page — a crucial point that many circulating code snippets get wrong.
The second block standardizes on the non-www version: the condition captures what comes after www. in a variable referenced as %1, then we rebuild the address without it. If you want the opposite — standardizing on www — replace it with this:
# Standardize on the www version (an alternative to the second block above)
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} !^localhost [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]Redirect loops behind a CDN or proxy
If your site sits behind a content delivery network or a reverse proxy that terminates encryption and then connects to your server over plain HTTP, .htaccess will see that %{HTTPS} isn't on even though the visitor really is browsing over HTTPS, so it redirects to HTTPS, the request arrives again in the same state, and so on forever. The fix is to check the header the proxy passes along:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>The two conditions together work with "and" logic: redirect only if the connection is unencrypted and the proxy hasn't told us the original was HTTPS. This breaks the loop, and enforcement stays in effect for visitors who really do arrive over HTTP.
Adding HSTS
Once your site is settled on HTTPS without any mixed content, you can add the HSTS header, which tells the browser not to attempt an unencrypted connection at all on future visits, so even that momentary redirect that could be intercepted disappears:
<IfModule mod_headers.c>
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
</IfModule>The always keyword ensures the header is sent even with error responses, and max-age is in seconds (here, a full year). Be careful with includeSubDomains: it covers all your subdomains, so if one of them has no certificate, it will become unreachable. Start with a short duration for testing, and see the HSTS explanation in the wiki before the final rollout. For the other security headers — content security policy, preventing framing and more — the full details are in the HTTP security headers guide.
Permalinks in WordPress
When you open Settings > Permalinks and choose a structure such as "Post name," what happens behind the scenes is that WordPress writes a block in .htaccess telling the server: "if someone requests a path that doesn't match an existing file or directory, pass it to index.php and let it handle it." Without this block, the home page works normally while every post returns a 404 error — a well-known symptom that confuses beginners after moving a site.
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPressThe two conditions !-f and !-d are the heart of the idea: -f means "an existing file" and -d means "an existing directory," and the exclamation mark negates them. In other words, passing to index.php only happens for paths that don't match anything real on disk — so images and CSS files keep being served directly without going through PHP. The E=HTTP_AUTHORIZATION line passes the authentication header to PHP, which is necessary for the authenticated REST API to work on some servers.
If you run into WordPress problems after editing — a 404 on every page, a white screen, or a dashboard that won't open — the guide to fixing common WordPress errors has a complete diagnostic sequence that starts with .htaccess itself, because it is the prime suspect in most of these cases.
Protecting sensitive files
Some files on any site contain secrets or open attack surfaces, and there is no legitimate reason for a visitor to reach them from a browser. Blocking them in .htaccess is a low-cost, high-return measure.
| File / directory | Why it must be blocked | Action |
|---|---|---|
wp-config.php | Contains the database credentials and security keys | Deny access completely |
.htaccess itself | Reveals your protection setup and rules to an attacker | Deny access (usually blocked by default) |
xmlrpc.php | A common target for brute-force and amplification attacks | Deny access if you don't use it |
wp-content/uploads/*.php | A path for executing malicious uploaded files | Prevent PHP execution in the directory |
readme.html / license.txt | They reveal the exact WordPress version | Deny access or delete them |
wp-login.php | The login gateway and the first target for guessing | Restrict it by IP address if possible |
.log, .sql and .bak files | Can be downloaded directly and expose your data | Deny access by extension |
| Directory listing | Reveals your site's structure and files | Options -Indexes |
# Deny access to sensitive files
<Files "wp-config.php">
Require all denied
</Files>
<Files "xmlrpc.php">
Require all denied
</Files>
# Prevent downloading of log, backup and database files
<FilesMatch "(?i)\.(log|sql|bak|old|swp|ini)$">
Require all denied
</FilesMatch>
# Disable directory listing
Options -IndexesFiles matches a specific file name, and FilesMatch matches a pattern using a regular expression. The (?i) prefix makes the match case-insensitive, so backup.SQL is blocked just like backup.sql. And Require all denied is the modern Apache 2.4 syntax for denying access to everyone.
And this block goes in an .htaccess file inside the wp-content/uploads directory specifically, not in the root — it is one of the highest-return protection measures in WordPress, because most compromises end with a malicious PHP file being uploaded to the uploads directory and then called:
# Put it in: wp-content/uploads/.htaccess
<FilesMatch "(?i)\.(php|phtml|php[0-9]|phps|pht)$">
Require all denied
</FilesMatch>Blocking IP addresses and controlling access
# Block specific addresses while allowing everyone else
<RequireAll>
Require all granted
Require not ip 203.0.113.45
Require not ip 198.51.100.0/24
</RequireAll>RequireAll means "all the conditions inside must be met": the general allow is met for everyone, but the "not this address" condition fails for the listed addresses, so they are blocked. You can write a single address or an entire range in CIDR notation, as in the last line, which blocks 256 addresses at once — a practical way to block a recurring nuisance coming from a single network.
The reverse is even more useful: restricting the login page to your own address alone, a measure that ends password-guessing attacks at their root if you have a static address:
# Allow only your address to open the login page
<Files "wp-login.php">
Require ip 203.0.113.45
</Files>These rules are one layer within a broader system; for the full picture, from plugins to permissions to two-factor authentication, see the guide to securing a WordPress site.
Preventing image theft (hotlinking)
Hotlinking means another site puts an image tag in its pages that points directly to a file on your server. The result is that its visitors load the image from your hosting: you pay for the bandwidth and carry the load, while it displays the content and reaps the traffic. On a site with many images, this can eat up a large share of your resources, especially if high-traffic sites link to your images.
<IfModule mod_rewrite.c>
RewriteEngine On
# Allow direct requests (no referrer)
RewriteCond %{HTTP_REFERER} !^$
# Allow your own domain
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?example\.com [NC]
# Allow search engines and preview platforms
RewriteCond %{HTTP_REFERER} !google\. [NC]
RewriteCond %{HTTP_REFERER} !bing\. [NC]
# Block all other sites from loading the images
RewriteRule \.(jpe?g|png|gif|webp|avif|svg)$ - [F,NC]
</IfModule>The logic is cumulative: each RewriteCond is an added exception, and the last rule only runs if all the exceptions fail. The first condition, !^$, is very important because it allows requests that carry no referrer at all — which is what happens when a user opens the image link directly, or when their browser hides the referrer for privacy reasons; without it, you would block legitimate users. The F flag means Forbidden, i.e. respond with a 403 error. Replace example.com with your domain, and don't forget to add your CDN's domain if you use one, or you will block your images from yourself.
Test the rule before you trust it: open a page on your site in a private browsing window and make sure all the images appear, then try pasting an image link into a social platform and look at the preview. And watch out for a special case: if you use a content delivery network, images are served from edge servers and the request may never reach .htaccess at all — in that case, hotlink protection is configured from the network's own dashboard, not here. Finally, if bandwidth usage is your main motive, the biggest gain usually comes from compressing images and serving them in modern formats, before any blocking rule.
Compression and browser caching
These two uses are among the fastest performance gains you can get with a few lines, because they reduce the size of what is transferred and the number of requests made in the first place on later visits.
Compressing text with mod_deflate
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css
AddOutputFilterByType DEFLATE application/javascript application/json
AddOutputFilterByType DEFLATE application/xml image/svg+xml
AddOutputFilterByType DEFLATE font/ttf font/otf
</IfModule>Each line adds content types that are compressed before being sent and then decompressed automatically by the browser. The gain on HTML, CSS and JavaScript files is huge — a reduction usually between 60% and 80% of the size — because they are text with repeating patterns. Notice what we didn't put on the list: JPEG, PNG and WebP images, video files and WOFF2 fonts. These are already compressed with their own algorithms, and recompressing them consumes CPU for negligible gain and may even increase the size slightly. For details on compression algorithms and the differences between them, see the Gzip and Brotli explanation in the wiki.
Caching with mod_expires
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 month"
ExpiresByType text/html "access plus 0 seconds"
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/javascript "access plus 1 year"
ExpiresByType image/webp "access plus 1 year"
ExpiresByType image/avif "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType font/woff2 "access plus 1 year"
</IfModule>The idea is to tell the browser: "keep this file in your cache and don't ask me about it again for this long." A returning visitor opens your site and downloads only the HTML, using the rest of the assets from their disk — a difference you can see with the naked eye. Notice that HTML is deliberately set to zero seconds: it is the only file that must always stay fresh, or your visitors will see old content after every update.
| File type | Suggested duration | Reason |
|---|---|---|
| HTML | 0 seconds | Changes with every content update |
| CSS / JavaScript | One year (with a fingerprint in the name) | Static; changes come with a new file name |
| Images (WebP/AVIF/JPEG) | One year | The file itself rarely changes |
| Fonts (WOFF2) | One year | Practically never change |
| PDF files and documents | One month | Updated occasionally |
robots.txt and sitemaps | One day | Change as the content grows |
A long duration is safe provided your files carry a fingerprint in their names that changes with every version (such as style.a3f9c1.css), which build tools and modern caching plugins do automatically. Without this fingerprint, you will have to wait for the duration to expire before visitors see your changes. The same behavior can be set with the more precise Cache-Control header:
<IfModule mod_headers.c>
<FilesMatch "(?i)\.(css|js|woff2|webp|avif|png|jpe?g|svg)$">
Header set Cache-Control "public, max-age=31536000, immutable"
</FilesMatch>
</IfModule>The immutable keyword tells the browser not to revalidate the file even when the page is refreshed manually — an extra gain with fingerprinted files. To understand the other caching layers (page cache, object cache, edge cache) and how they fit together, see caching explained.
Custom error pages
Apache's default error page is white and harsh and offers the visitor nothing. A custom page that carries your site's identity and shows a search field and links to the most important sections turns a visitor who was about to leave into one who keeps browsing.
ErrorDocument 400 /errors/400.html
ErrorDocument 401 /errors/401.html
ErrorDocument 403 /errors/403.html
ErrorDocument 404 /errors/404.html
ErrorDocument 500 /errors/500.htmlUse a relative path starting with a slash, as in the example. If you write a full address starting with https://, Apache will issue a 302 redirect instead of displaying the page, and the request loses the original error code — with the result that search engines see "an existing page" where they should see a 404, which is the soft 404 situation that harms indexing. And make sure the error pages themselves aren't blocked or inside a directory that requires authentication, or you will end up in a nested error path.
| Code | What it means | Common cause in the context of .htaccess |
|---|---|---|
| 403 Forbidden | Access forbidden | A Require rule or wrong file permissions |
| 404 Not Found | Path not found | A missing WordPress block or a wrong redirect rule |
| 500 Internal Server Error | General server failure | A syntax error or a directive for a module that isn't installed |
| 508 Loop Detected | Internal loop | A RewriteRule that rewrites itself endlessly |
| Repeated 301 / 302 | External redirect loop | Two conflicting rules (www and non-www, for example) |
Troubleshooting
First: a 500 error right after editing
This is the most common scenario, and its diagnosis is straightforward because the timing gives it away: if the error appeared the moment you saved the file, the cause is your edit with near certainty. The steps, in order:
Rename the file to htaccess-broken from the file manager and refresh the site. If it works again, you have confirmed the source and diagnosis is no longer guesswork. Open the broken copy and review the last block you added: did you close every IfModule or Files tag you opened? Does every double quote have a matching closing one? Is the module you are calling installed at all? Then restore the block line by line until the error appears, so you know the exact line.
For final confirmation, read the server's error log — in cPanel from the Metrics > Errors section, or the error_log file in your site's directory. The log usually gives you the line number and an explicit message such as Invalid command 'Header', which simply means mod_headers isn't installed and the fix is to wrap the block inside IfModule.
Second: an infinite redirect loop
The browser shows an ERR_TOO_MANY_REDIRECTS message or something similar, and the site doesn't open at all. The four most common causes: two conflicting www rules (one adds it and another removes it); forcing HTTPS behind a proxy that terminates encryption, as we explained in the previous section; WordPress's site address settings pointing to http:// while .htaccess forces https://, so they bounce the request back and forth; or a redirect rule whose source and destination fall on the same path.
The fix is diagnostic: disable all redirect rules by putting # at the start of their lines, and make sure the site opens. Then enable just one rule and test, and so on until the loop appears and you know the culprit. And clear the browser cache or test in a private window between each attempt, because the browser keeps previous 301 redirects and applies them before even asking the server.
Third: the file doesn't work at all
You wrote a rule, saved it, and nothing happens: no error and no effect. The possibilities, ordered from most to least likely:
The server isn't Apache. If it is Nginx, the file is ignored completely, as we explained. Check the Server header first, before anything else.
The AllowOverride directive is disabled. The server administrator can prevent .htaccess files from being read at all by setting AllowOverride None in the site configuration, a common performance measure on managed servers. In this case no error appears — the file is silently ignored. If you are on a server you own, set it to AllowOverride All; if you are on shared hosting, contact support.
The file's name or location is wrong. Make sure it is exactly .htaccess with the leading dot, without a hidden extension, and that it is inside the correct root of the domain you are testing, not in the account directory above it.
Another file overrides your rule. Look for .htaccess files in subdirectories, and look inside the file itself for a rule higher up that carries the [L] flag and matches the request before your rule gets its turn.
A caching layer in front of the server. If you have a content delivery network in front, or a caching plugin that generates static pages, the response may be served from the cache without the request ever reaching .htaccess. Clear the cache in every layer and then test again.
Fourth: a 403 on the whole site after adding a protection rule
This usually happens when you write Require all denied outside a Files or FilesMatch block, so the rule applies to the whole directory rather than to a specific file. Check that every deny rule is wrapped in a block that defines its scope. Another cause: a Require ip rule with an address that is no longer yours after your internet provider changed it.
When shouldn't you use .htaccess?
Despite everything above, the file isn't the ideal place for everything. Avoid it — or reduce your reliance on it — in these cases: when you have access to the server configuration, because directives there are read once and kept in memory, saving a disk read on every request. When redirect lists exceed a few hundred lines, since evaluating every rule on every request becomes a real cost and it is better to move them to a rewrite map (RewriteMap) or to the server level. And when the alternative is cleaner: denying access to a file can be achieved by moving it outside the publishing directory altogether, and for password protection a web application firewall may be a better fit.
The practical rule: use .htaccess for what changes and for what you need to apply immediately without administrative access — which covers almost everything a site owner on shared hosting needs. And move what has settled and stabilized into the server configuration whenever you have the permission.
Frequently asked questions
Does the .htaccess file work on Nginx hosting?
No, not at all. Nginx doesn't read the .htaccess file and has no equivalent, and this is a deliberate design decision: all its configuration is loaded once at startup and stays in memory, which is part of why it is fast. If you upload the file to an Nginx server, nothing happens — no error and no effect. The alternative is to write the directives inside the server block in the site's configuration file and then reload the service, which requires root access. LiteSpeed, on the other hand, reads the file with high Apache compatibility, which is why you find it so widely on shared hosting.
Why can't I see the .htaccess file in the file manager?
For two possible reasons. The first and most likely is that the file is hidden because its name starts with a dot, and you need to enable the option to show hidden files: in cPanel, from the Settings window at the top of the file manager with the Show Hidden Files option, and in FileZilla from the Server > Force showing hidden files menu. The second is that the file really doesn't exist, which is completely normal because it isn't required for the site to work. Create it yourself with the + File button and type the name .htaccess with the dot exactly and no extension.
Why did a 500 error appear after editing the file, and how do I fix it immediately?
Because Apache reads the file on every request and applies it immediately with no validation step, so any syntax error stops the server from processing the request entirely. The urgent fix: rename the file to htaccess-broken from the file manager, and the site will come back within seconds. Then open the file and review the last block you added — an unclosed tag, a missing quote, or a directive for a module that isn't installed on the server. Read error_log to find the exact line number, and restore the blocks one by one, testing after each one.
What is the difference between a 301 and a 302 redirect, and when do I use each? A 301 code means a permanent move: search engines transfer the old page's value and backlinks to the new one and replace the address in their index, and the browser caches it aggressively. Use it when changing a URL, merging two pages, moving a domain, or forcing HTTPS and standardizing www. A 302 means temporary: no value is transferred and the old address stays in the index. Use it for a page under maintenance or a seasonal offer that ends. Using a 302 for a permanent move is one of the most common migration mistakes, and it costs rankings that could have been saved entirely.
Does the .htaccess file really slow down my site? Yes, but by an amount that depends on its size and your traffic. Apache looks for the file and reads it on every request, walking the chain of directories from the root to the requested directory, and doesn't keep it in memory the way it does the server configuration. On an ordinary site with a file of a few dozen lines, the effect is imperceptible. But with hundreds of redirect rules or thousands of requests per minute, the effect shows up in the initial response time. If you have administrative access to the server, move stable rules into the vhost configuration, where they are read once at startup.
Can I write inside the BEGIN WordPress block?
Technically yes, but don't. WordPress considers everything between # BEGIN WordPress and # END WordPress its own and regenerates the whole block every time the permalink settings are saved, and sometimes during updates, so what you wrote is wiped without warning and you will be left puzzling over why your rule disappeared. Write your own rules above the start line or below the end line. The same principle applies to blocks created by caching and security plugins — respect the boundaries of every block marked with similar comments.
How do I block access to the wp-config.php file?
With a Files block in the .htaccess file in the site root containing Require all denied, which is the Apache 2.4 syntax for denying access to everyone. The file stays readable by PHP itself, so your site works normally, but nobody can open it from a browser. Add blocking of xmlrpc.php if you don't use it, blocking of .log, .sql and .bak files by extension via FilesMatch, and preventing PHP execution inside wp-content/uploads with a separate .htaccess file in that directory specifically.
Is .htaccess alone enough to protect my site?
No. .htaccess is one layer in a system. It is excellent at blocking paths, banning addresses and preventing file execution in specific directories — but it doesn't inspect request content, doesn't detect malware, and doesn't protect against a vulnerability in an outdated plugin. Combine it with regular core and plugin updates, strong passwords and two-factor authentication, correct file permissions (644 for files and 755 for directories), a web application firewall, and regular off-server backups. Security is stacked layers, not a single measure.
Sources
Frequently asked questions
Does the .htaccess file work on Nginx hosting?
No, not at all. Nginx doesn't read the .htaccess file and has no equivalent, and this is a deliberate design decision: all its configuration is loaded once at startup and stays in memory, which is part of why it is fast. If you upload the file to an Nginx server, nothing happens — no error and no effect. The alternative is to write the directives inside the server block in the site's configuration file and then reload the service, which requires root access. LiteSpeed, on the other hand, reads the file with high Apache compatibility, which is why you find it so widely on shared hosting.
Why can't I see the .htaccess file in the file manager?
For two possible reasons. The first and most likely is that the file is hidden because its name starts with a dot, and you need to enable the option to show hidden files: in cPanel, from the Settings window at the top of the file manager with the Show Hidden Files option, and in FileZilla from the Server > Force showing hidden files menu. The second is that the file really doesn't exist, which is completely normal because it isn't required for the site to work. Create it yourself with the + File button and type the name .htaccess with the dot exactly and no extension.
Why did a 500 error appear after editing the file, and how do I fix it immediately?
Because Apache reads the file on every request and applies it immediately with no validation step, so any syntax error stops the server from processing the request entirely. The urgent fix: rename the file to htaccess-broken from the file manager, and the site will come back within seconds. Then open the file and review the last block you added — an unclosed tag, a missing quote, or a directive for a module that isn't installed on the server. Read error_log to find the exact line number, and restore the blocks one by one, testing after each one.
What is the difference between a 301 and a 302 redirect, and when do I use each?
A 301 code means a permanent move: search engines transfer the old page's value and backlinks to the new one and replace the address in their index, and the browser caches it aggressively. Use it when changing a URL, merging two pages, moving a domain, or forcing HTTPS and standardizing www. A 302 means temporary: no value is transferred and the old address stays in the index. Use it for a page under maintenance or a seasonal offer that ends. Using a 302 for a permanent move is one of the most common migration mistakes, and it costs rankings that could have been saved entirely.
Does the .htaccess file really slow down my site?
Yes, but by an amount that depends on its size and your traffic. Apache looks for the file and reads it on every request, walking the chain of directories from the root to the requested directory, and doesn't keep it in memory the way it does the server configuration. On an ordinary site with a file of a few dozen lines, the effect is imperceptible. But with hundreds of redirect rules or thousands of requests per minute, the effect shows up in the initial response time. If you have administrative access to the server, move stable rules into the vhost configuration, where they are read once at startup.
Can I write inside the BEGIN WordPress block?
Technically yes, but don't. WordPress considers everything between BEGIN WordPress and END WordPress its own and regenerates the whole block every time the permalink settings are saved, and sometimes during updates, so what you wrote is wiped without warning and you will be left puzzling over why your rule disappeared. Write your own rules above the start line or below the end line. The same principle applies to blocks created by caching and security plugins — respect the boundaries of every block marked with similar comments.
How do I block access to the wp-config.php file?
With a Files block in the .htaccess file in the site root containing Require all denied, which is the Apache 2.4 syntax for denying access to everyone. The file stays readable by PHP itself, so your site works normally, but nobody can open it from a browser. Add blocking of xmlrpc.php if you don't use it, blocking of .log, .sql and .bak files by extension via FilesMatch, and preventing PHP execution inside wp-content/uploads with a separate .htaccess file in that directory specifically.
Is .htaccess alone enough to protect my site?
No. .htaccess is one layer in a system. It is excellent at blocking paths, banning addresses and preventing file execution in specific directories — but it doesn't inspect request content, doesn't detect malware, and doesn't protect against a vulnerability in an outdated plugin. Combine it with regular core and plugin updates, strong passwords and two-factor authentication, correct file permissions (644 for files and 755 for directories), a web application firewall, and regular off-server backups. Security is stacked layers, not a single measure.