11 Tricks for your htaccess file - this is how the htaccess works
One of the most popular and versatile methods to make settings on a website is by using a .htaccess file. This approach has numerous advantages over alternatives such as global or local configuration of a web server and is recommended in many situations because it provides an equally simple and efficient solution to a variety of common problems. At the same time, its use requires few technical prerequisites and restrictions, making the .htaccess file a kind of Swiss Army knife for working with websites in multiple ways.
Please note that you only have the htaccess file if you are using an Apache web server for web hosting. NginX web hosting does not have an htaccess file.
Contents:
What is the .htaccess file
How does an .htaccess file work?
How to create and edit an .htaccess file?
Practical tricks for .htaccess I: Securing requests with a password
Practical tricks for .htaccess II: Blocking and allowing IP ranges
Practical tricks for .htaccess III: Denying access to individual files or file types
Practical tricks for .htaccess IV: Denying access to individual files or file types
Practical tricks for .htaccess V: Disallowing directory browsing
Practical tricks for .htaccess VI: Redirecting HTTP errors
Practical tricks for .htaccess VII: Redirecting HTTP to HTTPS
Practical tricks for .htaccess VIII: Blocking crawlers, bots, and search engines
Practical tricks for .htaccess IX: Modifying PHP settings
Practical tricks for .htaccess X: Setting environment variables
Practical tricks for .htaccess XI: Redirecting with status code 301
What other possibilities does the .htaccess file offer?
What is the .htaccess file?
The .htaccess file allows website administrators to set their own directives, rules, and configurations in each directory, which are read, interpreted, and implemented by an Apache web server when accessed. It differs from the global or local settings of the web server mainly in that it is not stored in a central location outside the website, but instead is located directly in a callable path of a domain. This allows for simple, efficient, and reliable control and coordination, as well as the creation of a hierarchical structure with cascading instructions that can restrict access, make redirects, or analyse visitors based on different criteria and assign specific rights.
How does a .htaccess file work?
Like a PHP script or configuring programs in Linux, the .htaccess file is a simple text file where an administrator specifies the desired instructions in a standardized format. When a page is accessed, such as https://example.org/examples/htaccess, the Apache web server recursively accesses the directories - starting from example.org and gradually moving into the specified subdirectories. At each step, it checks for the existence of a .htaccess file and executes the instructions therein before moving to the next level. Since the Apache web server does not cache this information, the .htaccess file takes immediate effect upon creation - no restart or cache clearing is required for the htaccess file to take effect. However, some of the commands in .htaccess require corresponding modules that the Apache web server must load - the most prominent example being the mod_rewrite module responsible for redirects.
How to create and edit a .htaccess file?
As the .htaccess file is a plain text document, it can be created and edited with any ASCII code compatible editor such as gedit or mousepad on Linux, or Notepad on Windows. Crucial for execution by the Apache web server is the correct naming .htaccess, where the preceding dot signifies a hidden element that won't be displayed in a file manager. Like in many scripting languages and configuration files, comments can also be added by marking them with a preceding hash # as a non-executable part of the code. The method used to create or save the .htaccess file - whether through an FTP upload, directly via an SSH access, or through a web interface with a text editor - does not affect the outcome.
1. Practical Tricks for .htaccess: Securing Requests with Passwords
Once the question "What is a .htaccess file?" is answered, it's time to demonstrate some practical tricks and examples. One of the most important tasks for a .htaccess file is to provide a simple, efficient, and secure password protection for specific directories (and their subdirectories). This is an alternative to using Noindex via the robots.txt. It can be achieved with a few commands:
AuthType Basic
# Type of authentication
AuthName "Please enter login and password:"
# Title of the input mask
AuthUserFile /directory/with/passwordfile/.htpasswd
# Absolute path to a file with usernames and passwords
AuthPGAuthoritative Off
require valid-user
# Users allowed to access the protected area, here: all stored in the password file
The password file contains a combination of usernames and encrypted passwords and can be created using online editors or in Linux with the command htpasswd -c NAME. The name is freely selectable, but the default is .htpasswd. Additionally, with require, the user group can be further restricted, for example, by require user Name1 Name2 Name3.
2. Practical Tricks for .htaccess: Blocking and Allowing IP Ranges
Through a .htaccess file, access can also be blocked for IP addresses or ranges - particularly effective during DDoS attacks.
Order deny,allow
# Block first, then allow IPs
Deny from .t-online.de
# Block requests from users with the identifier t-online.de in general
Deny from 255.254 255.255
# Block all IPv4 addresses starting with 255.255. Multiple IPs or ranges can be separated by a space.
Allow from 255.255.0.1
# Exception to the block for IP 255.255.0.1
3. Practical tricks for .htaccess: Deny access to individual files or file types
It can also be useful to prohibit external access to specific file types for all visitors - such as configurations and .htaccess itself:
# Define file extension or name
Deny from all
# Blocks all external access
4. Practical tricks for .htaccess IV: Deny access to multiple files or file types
You can also combine multiple types together:
# Define a mask for all files below the directory
Order Allow,Deny
Deny from all
5. Practical tricks for .htaccess V: Prevent directory browsing
Another command allows you to allow or deny directory browsing if it does not contain index.html or index.php:
Option All -Indexes
# Prevents displaying directory contents, Indexes allows it
6. Practical tricks for .htaccess VI: Redirect HTTP errors
One of the most powerful methods of the .htaccess file is its ability to redirect requests by the Apache web server to other instances. For this to work, the Apache module mod_rewrite must be installed and activated. The format is simple: First, the website administrator defines a condition with the RewriteCond command, then specifies a new destination with RewriteRule.
One of the most popular tasks is redirecting visitors to an alternative page when encountering an error message like the HTTP Error 404 Not Found, which displays custom content instead of the standard text. This only requires a single line:
ErrorDocument 404 /directory/errors/404.html
The names of the directory and file can be freely chosen, but both must be within the website. Alternatively, it is also possible to specify an absolute internal or external domain address as the target:
ErrorDocument 404 www.example.org/errors/404.html
7. Practical Tips for .htaccess VII: Redirecting HTTP to HTTPS
Redirects are a very effective and versatile tool that can be used for many other purposes, such as redirecting all requests in plain text over HTTP to the encrypted HTTPS that has been the standard since 2015:
RewriteEngine On
RewriteCond %{HTTPS} !on
# Condition: Any connection not using HTTPS
# Alternatively: RewriteCond %{Server_Port} !=443
# Captures any external request not made on the HTTPS port 443
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
# Rule: Redirect to the address https://Domainname/URL
# Alternatively, absolute paths can also be specified here, for example:
# RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
# The square brackets indicate an HTTP status code, in this case 301 Moved Permanently
8. Practical Tips for .htaccess VIII: Blocking Crawlers, Bots, and Search Engines
It can also be useful to block unwanted crawlers, bots, and search engines from visiting a page altogether. Unlike a robots.txt file, this is done directly by the Apache web server and cannot be easily bypassed or ignored:
RewriteEngine On
RewriteBase /
# sets the root directory as the lowest instance
RewriteCond %{HTTP_USER_AGENT} ^Spam [OR]
# The redirection here is based on identifying visitors as User Agents
# Multiple conditions can be linked with logical operators like [OR]
RewriteCond %{HTTP_USER_AGENT} ^Spider [OR]
RewriteCond %{HTTP_USER_AGENT} ^Crawler [OR]
RewriteCond %{HTTP_USER_AGENT} ^Bot [OR]
RewriteCond %{HTTP_USER_AGENT} ^googlebot
# Completely blocks the website from being indexed by Google
# The last line should not have [OR] because the condition ends here
RewriteRule ^.* - [R=403,L]
# Redirects the affected User Agents to the HTTP Error Code 403 Forbidden
9. Practical Tricks for .htaccess IX: Changing PHP Settings
Through .htaccess, you can also directly influence and set variables of the PHP environment (e.g. PHP Memory Limit), such as:
php_value memory_limit 128M
# Sets the memory limit of the PHP interpreter to 128 megabytes
Of course, globally defined limits apply here - those planning to circumvent web hosting restrictions through this method will therefore fail, with few exceptions.
10. Practical Tricks for .htaccess X: Setting Environment Variables
In addition to PHP configuration, .htaccess also allows for redefining system environment variables:
SetEnv TZ Europe/Berlin
# Changes an environment variable used by the Apache web server, in this case the local timezone
These are manipulated only within the Apache web server, so this setting applies exclusively to the relevant queries and does not affect the entire server.
11. Practical Tricks for .htaccess: Redirecting with Status Code 301
Lastly, it is also possible to redirect individual or all requests to a domain to a new one, after a migration for example. For example, the 301 Redirect. Only one line is needed for this:
Redirect 301 /directory/file.html https://example.com/file.html
# Performs a Redirect 301 for a single file
RedirectMatch 301 /directory(.*) https://example.com/$1
# Redirects all requests from the original domain to example.com
What other options does the .htaccess file offer?
The options for using the .htaccess file are diverse and extensive, too much to cover in a single article. Due to its versatility and ease of implementation, it provides a simple solution to a variety of issues that can arise with an Apache web server. Another advantage of this method is that it can be quickly and immediately implemented and varied without the need to restart a server. Furthermore, it allows for a very detailed gradation of measures, such as on individual directories or files, and does not require access rights to the local or global configurations of the Apache web server. The main drawback is that separate access negatively affects the performance of the web server - therefore, for websites with high traffic, it is recommended to make settings through configuration files such as httpd.conf.
Secure the perfect Apache web hosting now
Go to Apache Web Hosting Comparison
Photo: Lawrence Monk on Pixabay
Write a comment
- Webhosting
- Webspace
- HTTP
Tags for this article
More web hosts
More interesting articles
Largest Web Hosting Providers in Austria 2025
What are the largest web hosting providers in Austria in terms of market share and search interest?
What influence does the choice of web hosting provider have on SEO? Location, speed, neighborhood
Placing one's own website on one of the first positions in Google search is one of the main concerns of every webmaster....