The htaccess file is one of the most powerful configuration files for your website. Whether you want to set up redirects, improve security or show custom error pages - with this configuration file you can arrange it all. In this complete guide we explain what this file does, how you use it, and give practical code examples that you can apply right away.

What is an htaccess file and what do you use it for?

The htaccess file (full name: .htaccess) is a configuration file for the Apache web server. The dot before the name indicates that it is a hidden file on Linux servers. The file contains instructions that the Apache server executes before a page is loaded.

With an htaccess file you can, among other things:

  • Set up URL redirects - Automatically forward visitors to new pages
  • Restrict access - Block or allow certain IP addresses
  • Password protection - Protect folders with a password
  • Custom error pages - Show your own 404 and 500 pages
  • Set browser caching - Improve load times with caching rules
  • Enforce HTTPS - Redirect insecure connections to HTTPS
  • Hotlink protection - Prevent others from loading your images

The file works per folder: an htaccess file in the root folder of your website applies to all files and subfolders, unless a subfolder has its own htaccess file that overrides the rules.

How do you create an htaccess file?

Creating an htaccess file is simple, but there are a few points of attention:

Through a text editor

  1. Open a text editor - Use Notepad++, VS Code or another editor (not Word!)
  2. Create a new file - Start with an empty file
  3. Save as ".htaccess" - Note: the file name starts with a dot and has no extension
  4. Upload through FTP - Place the file in the folder where it should apply

Through your hosting's file manager

Many web hosting providers offer a file manager in their control panel with which you can edit the htaccess file directly. In cPanel you find this under "File Manager".

Note: the file is hidden by default. In cPanel you have to enable the "Show Hidden Files" option to be able to see it.

The most important htaccess rules explained

Below we cover the most commonly used rules that you can apply in your configuration file. Each rule is explained with a working code example.

301 redirects (permanent forwarding)

A 301 redirect tells search engines that a page has permanently moved. This is important for your SEO because the link authority is transferred to the new URL.

Example code for a single redirect:

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

For more complex redirects you use mod_rewrite:

RewriteEngine On
RewriteRule ^old-path/(.*)$ /new-path/$1 [R=301,L]

Enforcing HTTPS

Automatically forward all visitors from HTTP to HTTPS:

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

Adding or removing WWW

To always use the www version:

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

Htaccess for better performance: caching and compression

A well-configured htaccess file can considerably improve your website's load time. Here are the most important performance optimizations:

Setting browser caching

By setting browser caching, your visitor's browser does not have to download all files again on every visit:

# Set cache per file type
<IfModule mod_expires.c>
ExpiresActive On
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"
ExpiresByType text/html "access plus 1 hour"
</IfModule>

Activating GZIP compression

Compression reduces the file size of your web pages by 60-80%, which drastically improves load time:

<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml
AddOutputFilterByType DEFLATE text/css application/javascript
AddOutputFilterByType DEFLATE application/json application/xml
</IfModule>
OptimizationExpected improvementDifficulty
Browser caching20-40% faster on returnEasy
GZIP compression60-80% smaller filesEasy
Keep-Alive10-20% faster connectionEasy
Disabling ETagsFewer unnecessary requestsEasy

Improving security with htaccess

The htaccess file is also a powerful tool for your website's security. Here are the most important security rules:

Disabling directory listing

Prevent visitors from viewing the contents of your folders:

Options -Indexes

Blocking access to sensitive files

Protect configuration files and other sensitive data:

# Block access to .htaccess itself
<Files .htaccess>
Order Allow,Deny
Deny from all
</Files>

# Block access to wp-config.php (WordPress)
<Files wp-config.php>
Order Allow,Deny
Deny from all
</Files>

Blocking IP addresses

Block specific IP addresses that cause unwanted traffic:

Order Allow,Deny
Deny from 192.168.1.100
Deny from 10.0.0.0/24
Allow from all

Prevent other websites from loading your images directly (which costs you bandwidth):

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https://(www\.)?yourdomain\.nl [NC]
RewriteRule \.(jpg|jpeg|png|gif|webp)$ - [NC,F,L]

Setting up custom error pages with htaccess

Default error pages are ugly and unhelpful. With the htaccess file you can set up your own error pages that match your website design:

ErrorDocument 400 /errors/400.html
ErrorDocument 401 /errors/401.html
ErrorDocument 403 /errors/403.html
ErrorDocument 404 /errors/404.html
ErrorDocument 500 /errors/500.html
Error codeMeaningCommon cause
400Bad RequestInvalid request by the browser
401UnauthorizedAuthentication required
403ForbiddenAccess denied by server rules
404Not FoundPage does not exist or has been removed
500Internal Server ErrorError in server configuration or script

Htaccess and WordPress: specific applications

WordPress makes intensive use of the htaccess file for the permalink structure. The default WordPress htaccess block looks as follows:

# 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

Always place your own rules above or below this block, never in between. WordPress can overwrite the block when you change permalink settings.

Common mistakes in the htaccess file

An error in your configuration file can make your entire website unreachable. These are the most common mistakes and how to avoid them:

  • Typos in rules - A single typo can cause a 500 error. Check every rule carefully
  • Infinite redirect loops - Conflicting redirect rules can cause a loop. Always test after changes
  • No backup - Always make a copy before you edit the file
  • Wrong file name - The file must be named exactly ".htaccess", without an extension
  • Rules in the wrong order - The order of rules matters. Specific rules must come before general ones
  • Not testing - Always test your changes in a test environment before you put them live

Htaccess vs. Nginx: what if you do not use Apache?

The htaccess file works only on Apache web servers. If your web hosting uses Nginx, you need a different approach. Nginx does not read htaccess files but uses a central configuration file (nginx.conf).

Most of the functionality of an htaccess file is also available in Nginx, but the syntax is completely different. Check with your hosting provider which web server is used.

Frequently asked questions about the htaccess file

Can I have multiple configuration files?

Yes, you can place your own htaccess file in every folder. Rules in a subfolder file take priority over rules in the root folder.

How do I test this file without breaking my live site?

Use a test environment or staging server. You can also test the Apache configuration with the command apachectl configtest if you have server access.

My site gives a 500 error after editing the file. What now?

Restore the original file from your backup. If you do not have a backup, rename or delete the htaccess file through FTP or the file manager. Your site should then work again.

Does this configuration file work on all hosting?

Only on Apache web servers. Most shared hosting uses Apache, but check this with your provider. LiteSpeed servers also support this type of configuration file.

Advanced htaccess techniques for experienced users

In addition to the basic applications, the configuration file also offers advanced possibilities for experienced web developers and server administrators. These techniques require more knowledge but can make a big difference to the performance and security of your website.

Content Security Policy headers

With security headers you protect your visitors against cross-site scripting (XSS) and other attacks. Add these headers to your configuration file:

<IfModule mod_headers.c>
Header set X-Content-Type-Options "nosniff"
Header set X-Frame-Options "SAMEORIGIN"
Header set X-XSS-Protection "1; mode=block"
Header set Referrer-Policy "strict-origin-when-cross-origin"
</IfModule>

Conditional rules based on the browser

You can apply specific rules based on the visitor's browser or device. This is useful for serving optimized content to different users. Use RewriteCond with the HTTP_USER_AGENT variable to create browser-specific rules.

Rate limiting and brute-force protection

Protect your login page against brute-force attacks by limiting the number of requests per IP address. This is especially important for WordPress sites where the wp-login.php page is often the target of automated attacks. Combine this with password protection through the configuration file for an extra security layer.

Setting environment variables

With SetEnv and SetEnvIf you can set environment variables that can be read by your application. This is useful for configuring different settings per environment, such as distinguishing between production and development.

The htaccess file is an indispensable tool for every website owner. From redirects and caching to security and performance optimization - the possibilities are endless. With the examples in this article you can get started right away to make your website faster, safer and easier to find.

Do not forget to always make a backup before you make changes, and always test new rules in a test environment. With a well-configured htaccess file you get the most out of your web hosting and offer your visitors the best experience.

Do you want to know more about hosting options and how to get the most out of your server configuration? Then take a look at our extensive guide on web hosting in which we cover all aspects of hosting, including server configuration and performance optimization. With the right combination of hosting and server settings you build a fast, secure and reliable website.

Htaccess: advanced redirects and URL rewriting

One of the most powerful applications of the htaccess file is rewriting and forwarding URLs. This is essential for SEO and user experience.

301 redirects for SEO

When you change the URL structure of your website, you have to set up 301 redirects to inform search engines that the page has permanently moved. Without redirects you lose the built-up SEO value of the old URLs and visitors get a 404 error. A 301 redirect transfers the largest part of the link value to the new URL. Use specific redirects per page instead of wildcard rules for the most accurate forwarding.

URL rewriting with mod_rewrite

The mod_rewrite module allows you to rewrite URLs without the visitor noticing. With it you create readable URLs that both users and search engines appreciate. A URL such as yoursite.nl/product.php?id=123 is rewritten to yoursite.nl/product/phone-case. The RewriteRule directive in your htaccess file determines how the URL is converted, while RewriteCond sets conditions under which the rule is applied.

Commonly used htaccess redirect rules

GoalTypeApplication
HTTP to HTTPS301 redirectForce a secure connection
www to non-www301 redirectSet the canonical URL
Old URL to new301 redirectAfter site restructuring
Add trailing slash301 redirectURL consistency
Temporary forwarding302 redirectMaintenance page

Htaccess: security and access control

The htaccess file is a powerful tool for securing your website and restricting unauthorized access to sensitive files.

Directory protection

Protect sensitive directories such as your admin panel, configuration folders and upload folders with password protection through htaccess. Combine this with IP restriction to give only specific IP addresses access to management interfaces. Also block directory listing so that visitors cannot browse through your folder structure. These simple measures prevent unauthorized people from gaining access to files that are not intended for public use.

Hotlinking is linking directly to files on your server from other websites, so that they use your bandwidth. With htaccess you can set up hotlink protection that only allows requests from your own domain and trusted sources such as search engines. This saves bandwidth and server resources. Set an alternative image that is shown when someone tries to hotlink your files.

Do you want to know more about website security? Read our article on website security tips for additional security measures.

Htaccess: frequently asked questions and best practices

When working with the htaccess file, many of the same questions come up. Below we answer the most important questions and share best practices for safe use.

Does htaccess affect website speed?

Yes, but the impact can be both positive and negative. Well-configured htaccess rules for caching and compression improve speed considerably. Too many or poorly written rules can slow the server down because Apache has to parse the htaccess file on every request. For websites with very high traffic it is more efficient to place rules directly in the Apache configuration instead of in htaccess, but for most websites the impact is negligible.

Can I use htaccess on Nginx?

No, the htaccess file is specific to the Apache web server. Nginx uses a different configuration system through server blocks in the nginx.conf file. If you switch from Apache to Nginx, you have to translate your htaccess rules to the Nginx syntax. There are online converters that can automatically translate the most common rules, but complex configurations require manual adjustment.

Best practices for htaccess

  • Always make a backup before you make changes to the htaccess file
  • Test every change immediately by loading the website in your browser after saving
  • Add comments to each rule or block so that you know later why a rule was added
  • Keep the file compact by only including necessary rules
  • Use specific rules instead of broad wildcards to avoid unintended effects
  • Check for duplicates because conflicting rules cause unpredictable behavior

Htaccess: summary and essential rules

With the right knowledge, the htaccess file is an indispensable tool for configuring your website. Here we summarize the essential rules that every website should have.

Minimum htaccess configuration

Every website that runs on an Apache server should have at least the following configurations in the htaccess file. A 301 redirect from HTTP to HTTPS to serve all visitors over a secure connection. Browser caching headers for static files to improve load speed. GZIP compression for text-based files to reduce the transfer size. Protection against directory listing to prevent visitors from browsing through your folder structure. Blocking access to sensitive files such as wp-config.php and .htaccess itself.

When to call in professional help

Although many htaccess configurations can be done yourself, there are situations in which professional help is wise. With complex URL rewrites for large websites with hundreds of pages, a mistake is quickly made. When configuring advanced security rules, a wrong setting can make your website unreachable. When solving conflicts between htaccess rules and CMS configurations, experience is valuable. A web developer or your hosting provider can help you with these more complex configurations.

Htaccess: advanced security rules

The htaccess file offers powerful possibilities for securing your website at server level. With IP-based access control you can block specific IP addresses or, conversely, give only certain addresses access to sensitive directories such as the admin panel. Hotlink protection prevents other websites from linking directly to your images and thereby using your bandwidth. Set up custom error pages through the htaccess file so that visitors who reach a non-existent page see a useful error message with navigation back to working pages.

Htaccess and performance headers

Use the htaccess file to set performance-related HTTP headers. The Expires and Cache-Control headers determine how long browsers may cache files locally. The Content-Security-Policy header protects against cross-site scripting attacks. The X-Content-Type-Options header prevents MIME-type sniffing. By configuring these headers correctly you improve both the performance and the security of your website without changes to the application code.

Testing and debugging htaccess

Errors in the htaccess file can make your entire website unreachable. Therefore always test changes first in a staging environment before you deploy them to production. Use online htaccess testers to validate your rules without risk. When an error occurs, rename the htaccess file temporarily to check whether the problem is related to it. Always keep a backup of the working htaccess file at hand so that you can quickly fall back in case of problems.