The .htaccess file is one of the most powerful and most dangerous files on your web server. You can use it to set up redirects, secure your site and rewrite URLs. But one typo and your site shows nothing but Error 500.

What is .htaccess?

.htaccess (hypertext access) is a configuration file for Apache web servers. It sits in the root of your website and influences how the server handles requests.

The dot at the front means it is a hidden file. In your FTP client you may need to enable "show hidden files".

What do you use .htaccess for?

  • Redirects: Send URLs to other locations
  • URL rewriting: Clean URLs without a .php extension
  • Security: Protect folders, block IPs
  • Caching: Set browser caching
  • Forcing HTTPS: Redirect HTTP to HTTPS
  • Error pages: Set a custom 404 page

Commonly used .htaccess rules

Forcing HTTP to HTTPS

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

www to non-www (or the other way around)

# From www to non-www
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

# From non-www to www
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

Specific redirect

Redirect 301 /old-page https://yoursite.com/new-page

Custom 404 page

ErrorDocument 404 /404.html

Password-protecting a folder

AuthType Basic
AuthName "Protected area"
AuthUserFile /path/to/.htpasswd
Require valid-user

Blocking an IP address

Deny from 123.456.789.000

Browser caching

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

WordPress and .htaccess

WordPress uses .htaccess for permalinks. The default content:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Do not change anything between BEGIN and END WordPress: that block gets overwritten by WordPress.

Editing .htaccess safely

  1. Make a backup: Download the current file
  2. Edit locally: Use a proper text editor (not Word!)
  3. Upload and test: Load your site right after uploading
  4. Mistake? Restore the backup: Overwrite it with your backup

Common problems

Error 500 after a change

A syntax error in your .htaccess. Restore your backup or remove the recent change.

Redirect loop

Your redirect points to a URL that redirects again. Check the order of your rules.

Rules don't work

Mod_rewrite may not be active. Or your server is nginx (which does not use .htaccess).

Note: nginx does not use .htaccess

.htaccess only works on Apache servers. Nginx has its own configuration system. If you're on nginx, you need to ask your server administrator to make changes.

Frequently asked questions

Can I have .htaccess per folder?

Yes, every folder can have its own .htaccess that overrides the parent one.

How do I know if my server is Apache?

Check your hosting panel or ask your provider. Or look at your site's server headers.

Is .htaccess slow?

A little. Apache has to read the file on every request. For high-traffic sites, server config is faster.

Hosting at Theory7

Commonly used .htaccess tricks

Forcing HTTP to HTTPS

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

All visitors are automatically sent to the secure version of your site.

Adding or removing www

Adding it (non-www to www):

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

Removing it (www to non-www):

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

Custom error pages

ErrorDocument 404 /404.html
ErrorDocument 500 /500.html

Show your own page instead of the default server error.

Setting browser caching

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

Browsers store files longer, which makes your site faster for returning visitors.

Blocking hotlinking

RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https://(www\.)?yoursite\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [F]

Prevent others from loading your images directly and using your bandwidth.

.htaccess and WordPress

WordPress uses .htaccess for permalinks. This is the default content:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Don't edit this block manually: WordPress manages it itself. Add your own rules above or below it.

Editing .htaccess safely

  1. First make a backup of your current .htaccess
  2. Test changes locally or on a staging environment
  3. Upload and test immediately, since syntax errors make your site unreachable
  4. If there are problems: restore the backup

Common mistakes

500 Internal Server Error

Syntax error in your .htaccess. Check the rules carefully. A single typo breaks everything.

Redirect loop

Your rules point to each other. Check for conflicting RewriteRules.

File not visible

.htaccess is a hidden file (it starts with a dot). Turn on "show hidden files" in your FTP client.

Advanced .htaccess techniques

Improving security

Block access to sensitive files:

<FilesMatch "^(wp-config\.php|\.htaccess|readme\.html)$">
Order Allow,Deny
Deny from all
</FilesMatch>

Disable directory browsing:

Options -Indexes

Protect against clickjacking:

Header always set X-Frame-Options "SAMEORIGIN"

Performance optimization

Enable compression:

<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/css
AddOutputFilterByType DEFLATE application/javascript application/json
</IfModule>

Rewriting URLs

Redirecting an old URL to a new one:

Redirect 301 /old-page https://site.com/new-page

Redirecting all requests to a maintenance page (except your IP):

RewriteCond %{REMOTE_ADDR} !^123\.456\.789\.000
RewriteCond %{REQUEST_URI} !^/maintenance\.html$
RewriteRule ^(.*)$ /maintenance.html [R=302,L]

.htaccess alternatives

Nginx

On Nginx servers, .htaccess does not work. There you use configuration in nginx.conf or server blocks. Many rules are similar but with different syntax.

Plugin-based

Some functions can also be handled through WordPress plugins, such as redirects (Redirection plugin) or security headers (various security plugins).

.htaccess is a powerful configuration file that offers many possibilities. Experiment carefully, make backups, and you have a flexible tool for website optimization.

The .htaccess file is one of the most powerful configuration files on an Apache web server. With a few lines of code you can fundamentally change your website's behavior, from URL rewriting to access restriction, from caching to security.

Commonly used .htaccess rules

A few handy rules you can add to your .htaccess:

  • Redirect from HTTP to HTTPS for a secure connection
  • Block access for specific IP addresses
  • Set browser caching for faster load times
  • Disable directory listings for better security
  • Set custom 404 error pages

Be careful with changes

The .htaccess file is sensitive: a small typo can take down your entire website. Always make a backup before making changes. If your website stops working after a change, you can restore the backup file via FTP.

Always test changes on a staging environment or test server before you put them live. And document what you add, so you still know later why certain rules are there.

Alternative: NGINX

Note that .htaccess only works on Apache servers. If your hosting uses NGINX, you need to make configuration changes elsewhere. Ask your hosting provider how to make similar settings on an NGINX server.

The .htaccess file gives you control over your Apache web server. From redirects to caching headers, the possibilities are endless. Be careful with changes, since a typo can make your site unreachable. Always test on a copy and keep a backup on hand. With a bit of practice, .htaccess becomes an indispensable tool in your website management toolkit. Study the possibilities and apply them where needed.

With .htaccess you determine how Apache serves your website. From simple redirects to complex rewrite rules: the possibilities are enormous. Take the time to learn the syntax and experiment on a test server. A solid .htaccess configuration makes your website faster, safer and easier to find. It is a skill every webmaster should master.

Every .htaccess command you learn makes you a better webmaster. Start with the basics and expand your knowledge step by step. Redirects, caching headers, security rules: they are all valuable skills. Document your configuration so you know later why certain rules are there. A well-maintained .htaccess file is a sign of professional website management.

At Theory7 we run LiteSpeed web servers that support .htaccess. Need help with your configuration? Our support team is happy to help.

Get started with .htaccess now.

Learn to master .htaccess today.

Overview of commonly used htaccess file rules

The htaccess file offers countless ways to configure your website. Below you'll find a handy overview of the most used rules you can apply in your htaccess file.

Functionhtaccess file ruleApplication
HTTP to HTTPS redirectRewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]Enforce a secure connection
www to non-wwwRewriteRule ^(.*)$ https://example.com/$1 [R=301,L]Set a canonical URL
Custom 404 pageErrorDocument 404 /404.htmlShow your own error page
Blocking directory listingOptions -IndexesHide folder contents
Gzip compressionAddOutputFilterByType DEFLATE text/htmlFaster load times
Browser cachingExpiresByType image/jpeg "access plus 1 year"Cache static files
Blocking an IPDeny from 123.456.789.0Keep out unwanted traffic
Hotlink protectionRewriteRule \.(jpg|png|gif)$ - [F]Protect images

Tips for safely editing your htaccess file

Before making changes to your htaccess file, it's wise to always make a backup first. A mistake in the htaccess file can make your entire website unreachable. Preferably test changes first in a test environment before rolling them out to your live website.

The htaccess file is a powerful but also fragile configuration file. Always use the correct syntax and check after every change whether your website still functions correctly. If in doubt, it's best to have the htaccess file edited by someone with technical experience.

Htaccess File: Performance Optimization

The htaccess file is a powerful tool for improving your website's performance without changing server configuration files.

Setting browser caching

With the htaccess file you can set browser caching headers that tell the browser how long files may be stored locally. Static files such as images, CSS and JavaScript rarely change and can be cached for months. HTML files change more often and get a shorter cache time. By setting browser caching correctly, returning visitors load your website significantly faster because they don't have to re-download many files.

Enabling GZIP compression

GZIP compression reduces the size of files sent to the browser by 60 to 80 percent. This reduces the amount of data sent over the network and speeds up load time considerably. Via the htaccess file you enable compression for text-based files such as HTML, CSS, JavaScript, XML and JSON. Binary files such as images and video don't benefit from GZIP compression because they are already compressed.

Performance settings overview

SettingEffectCache timeFile type
Browser caching imagesFaster repeat visits1 yearJPG, PNG, WebP, SVG
Browser caching CSS/JSFewer downloads1 monthCSS, JavaScript
Browser caching HTMLFresher content1 hour to 1 dayHTML
GZIP compression60-80% smallerNot applicableText files
Disabling ETagsFewer requestsNot applicableAll files

Htaccess File: Common Mistakes and Solutions

A mistake in your htaccess file can make your entire website unreachable. Know the common mistakes and how to prevent them.

500 Internal Server Error

The most common mistake after editing an htaccess file is the 500 Internal Server Error. This means there's a syntax error in the file. Always make a backup of your original htaccess file before making changes. If you get a 500 error, restore the backup file via FTP. Add changes step by step and test after each change whether the website still works correctly.

Preventing redirect loops

Incorrectly configured redirects can lead to infinite loops where the browser keeps getting redirected endlessly. This results in an error message saying the page has been redirected too many times. Check your redirect rules for circular references. Use RewriteCond conditions to prevent rules from being applied to URLs that already meet the desired criteria.

Also read our in-depth article about the complete guide to htaccess for even more advanced configurations.

Htaccess File: Frequently Asked Questions

When working with the htaccess file, many of the same questions come up. Below we answer the most frequently asked questions with clear explanations.

Where do I find the htaccess file?

The htaccess file is located in the root directory of your website, the same folder as your index.php or index.html file. Because the filename starts with a dot, it's a hidden file that isn't visible by default in most file managers. In FileZilla you enable the display of hidden files via Server, Force showing hidden files. In DirectAdmin's file manager the file is visible by default.

Can I have multiple htaccess files?

Yes, you can place an htaccess file in any directory of your website. The htaccess file in a subfolder overrides the rules of the htaccess file in the parent folder for that specific directory. This is useful for applying specific rules to certain sections of your website, such as password protection for an admin folder or different caching rules for a media directory.

Frequently asked questions

  • Is htaccess safe to edit? Yes, as long as you make a backup before making changes. A mistake can make your website unreachable, but this is easily fixed by restoring the backup file.
  • Does htaccess work on all servers? Htaccess only works on Apache web servers. Nginx and LiteSpeed use a different configuration system, although LiteSpeed offers limited htaccess compatibility.
  • How do I test my htaccess rules? There are online htaccess testers where you can enter and test your rules without putting them on your live server. Always test in a staging environment before rolling out changes to production.
  • Can I use htaccess for PHP settings? Yes, you can set various PHP configurations via htaccess, such as memory limits, upload sizes and error reporting levels.

Htaccess File: Summary and Essential Configurations

The htaccess file is a powerful but simple tool for configuring your website. Here we summarize the essential configurations every website should have.

The five must-have configurations

Every website should have at least these five configurations in the htaccess file. First: a redirect from HTTP to HTTPS for secure connections. Second: browser caching headers that improve load speed for returning visitors. Third: GZIP compression that reduces file size by 60 to 80 percent. Fourth: disabling directory listing so visitors can't browse through your folders. Fifth: protection of sensitive files by blocking direct access.

Maintenance and documentation

Treat your htaccess file as an important configuration document. Add a comment to every rule or block describing what the rule does and when it was added. Make a backup before making changes. Test every change immediately in your browser. Keep a version history so you can revert to an earlier configuration if problems occur. With this discipline, your htaccess file stays organized, understandable and maintainable in the long run.

Htaccess File: Optimization for Specific CMS Systems

The htaccess file requires specific configurations depending on the CMS used. For WordPress, the default htaccess file contains the rewrite rules for permalinks, but you can extend it with caching headers and security rules. For Joomla, the default SEF URL rules are already included, but extra rules for blocking common attack vectors are recommended. With a custom PHP application, you write all URL routing rules yourself in the htaccess file. Make sure your CMS-specific rules don't conflict with your own custom rules by carefully determining the order.

Common mistakes in the htaccess file

Avoid the most common mistakes when editing your htaccess file. Never forget to make a backup before rolling out changes. Check that RewriteEngine On is enabled before adding rewrite rules. Avoid infinite redirect loops by formulating your conditions carefully. Test every change immediately after implementation and check both the functionality and the performance of your website.