Using .htaccess file, you can control various aspects of the Apache webserver (and its variants.) This article will explain what is htaccess file, what you need to know to set up special error pages, password-protect directories, redirects, and more.
What is htaccess file?
The .htaccess is a web server configuration file that controls how a web server responds to various incoming requests. Several web servers support this file and format, including the Apache web server which is the most popular among commercial web hosting companies.
.htaccess files operate at the level of the directory they are located in, and they can override global configurations set at higher directory levels by another .htaccess file. But generally, there usually is one file in the main directory of the website.
The main uses for .htaccess files include setting up URL redirect or URL rewriting rules, protecting folders and webpages with passwords, displaying custom error pages for common error messages, directing bot behavior, indexing, and many more. So now that we have specified What is htaccess file, we are going to get deeper into .htaccess file and see what can we do with it.
How to Find .htaccess File?
Every folder (directory) on the server could have its own .htaccess file. However, normally there is just one such file in your web root folder – that’s the folder that all the content of your website is kept in, usually named something like public_html or www.
If you have multiple websites on the same server, there usually will be a single directory holding all your website subdirectories, with a .htaccess file in the main directory and more .htaccess files in each website subdirectory. As we mentioned, this file operates at the directory level, therefore those subdirectory .htaccess files can overrule the one above them for customizing rules about the one website they’re configuring.
Where is the .htaccess File in WordPress?
To access the .htaccess file on your WordPress website, you need direct access to your website so you can connect directly through an FTP client such as FileZilla. Once you connect to your site using FTP with Filezilla, you will see a tree of directories on the web server.
On the top-right quadrant, you will find a directory or folder named after your website’s domain name. That’s the root directory. Select it and check the files under it, you should find your .hataccess file.
How to Edit .htaccess?
Before trying to change or edit your .htaccess file, you need to take some safety measures. Making direct changes to your website always includes some risk. If you aren’t careful or don’t know exactly what you are doing, you can damage your website or even break it.
First, take in mind that it’s best practice to back up your website and files before making any changes to them; especially when you are making changes to configuration files such as .htaccess.
Second, do not make or save changes directly to the file on the server. Download your .htaccess file from your WordPress website or any other type, then make the changes on your own computer and check them before committing the changes to the real file on the server.
You can make your desired changes to the file and then replace the original file on the server through the FTP client. Another way is to directly edit the file on the server, though this is not recommended. You can right-click on the file in FileZilla or another FTP client, and click edit to open and edit the file using your desktop text editor, then save and close.
Why Can’t I Find .htaccess File?
On most file systems, filenames that begin with a dot (such as .htaccess) are hidden files. These files are not shown by default. However, you can make the system show them.
In your FTP client or File Manager there usually is a setting to show hidden files. The setting, however, may be located differently in every program. Generally, you can find it under menus such as Settings, Folder Options, View, Preferences, etc.
If you can’t find the .htaccess file in the root folder of your website, there’s a chance that the file doesn’t exist; in other words, it has not been created yet.
How to Create a .htaccess File?
On a WordPress website, you can prompt your WordPress to generate the file by visiting Settings > Permalinks in your WP dashboard, then click on the Save Changes button. Although, you don’t actually need to change anything.
If you are not using WordPress or just want to create the file in another way, do the following:
- Start a new file in a plain text editor, like Notepad++ or Windows’s Notepad.
- Save the file in ASCII format (not UTF-8 or any other format), with the name .htaccess
- Make sure that your file does not have an extension like .text, because editors usually add an extension. If they do, rename the file and delete the extension, just leave the .htaccess
- Upload your file to the root directory of your website using either an FTP client (e.g. FileZilla) or a browser-based file manager.
What Can You Do with .htaccess File?
Now that you know where the .htaccess file is on your web server or WordPress website server, and how you can edit it, or create it, It’s time we talk about the things we can do with .htaccess file. There are so many things that we cannot cover in this post, but we will explain its most important functions for you.
When users send a request to a website, usually for a web page or file, or data from an application, the server tries to answer that request, and if it fails, sends back an error indicating what kind of problem is encountered.
These different errors have different codes. The most familiar one maybe a 404 error, or a page not found error. There are many other error codes that the server can respond with.
Client Request Errors:
- 400 — Bad Request
- 401 — Authorization Required
- 402 — Payment Required (not used yet)
- 403 — Forbidden
- 404 — Not Found
- 405 — Method Not Allowed
- 406 — Not Acceptable (encoding)
- 407 — Proxy Authentication Required
- 408 — Request Timed Out
- 409 — Conflicting Request
- 410 — Gone
- 411 — Content-Length Required
- 412 — Precondition Failed
- 413 — Request Entity Too Long
- 414 — Request URI Too Long
- 415 — Unsupported Media Type.
- 500 — Internal Server Error
- 501 — Not Implemented
- 502 — Bad Gateway
- 503 — Service Unavailable
- 504 — Gateway Timeout
- 505 — HTTP Version Not Supported.
There’s a default error handling for any of these cases. that is the server just returns the error message or status code to the browser, and the browser will simply show the error to the user. However, sometimes the default is not ideal. This is where .htaccess is leveraged to change the response.
Specifying Error Documents
You can create an HTML document for each error code that you want to customize on your website, and then tell the webserver to show them instead, using .htaccess. It is very simple to do, you just need to add a few lines like below to the file:
ErrorDocument 400 /errors/bad-request.html ErrorDocument 401 /errors/auth-requested.html ErrorDocument 403 /errors/forbidden.html ErrorDocument 404 /errors/page-not-found.html ErrorDocument 500 /errors/server-error.html
Alternatives to .htaccess for Error Handling
Alternatively, you can use WordPress itself or another Content Management System that you are using to do the job.
Specify a Default File for a Directory
When a request is made to a web server for a URL that does not specify a file name, the default for most web servers is that the URL refers to the last directory itself directory. The browser tries to show a simple list of the files on that directory on the server.
On the other hand, the Apache webserver tries to answer the request with a default file, which is by default index.html. But that may not be what you want, so you can specify a default file (e.g. home.html, site.php, etc.) for that directory using the .htaccess file.
.htaccess allows you to set the default page for a directory easily:
DirectoryIndex [filename here]
If you want your default to be home.html it’s as easy as:
If you want to set other files with other names as default for lower directories, there are two ways:
Method 1: Create a .htaccess file inside every directory you want to configure and make your directory settings there.
Method 2: Add more default file names at the end of the top-level .htaccess DirectoryIndex line. It affects all the subdirectories as well, and where it doesn’t find the default file, it will look for the next file name in line. For example:
DirectoryIndex index.php index.shtml index.html
URL Redirects and URL Rewriting
One of the most common uses of .htaccess files is URL redirects. This is very important for user experience on your site, as well as your internet search result rankings.
301 vs. 302 Redirects
URL redirects should be used when the URL for a document or resource has changed. From a browser standpoint, there are two types of redirects, 301 and 302. (These numbers refer to the error code generated by the webserver.) 301 means “Permanently Moved,” while 302 means “Moved Temporarily.” 301 is preferred because it preserves any SEO equity the original URL had and passes it on to the new URL.
To redirect one page to another URL, the code is:
Redirect 301 /relative-url.html http://example.com/full-url
Here, the relative URL is relative to the directory containing the .htaccess file.
What if your entire site has moved to a new URL? Easy.
Redirect 301 / http://newurl.com
Password Protection with .htaccess Permissions
You can use .htaccess to restrict access to certain directories on a per-user basis. This was actually the original function of this file.
The usernames and passwords are stored in pairs separated with a “:” character, each set in a single line in a separate file named .htpasswd. The passwords are hashed, however, meaning that they’re not simple text. when a user tries to authenticate, their password is run through a hashing algorithm and if the result is the same as the hashed password stored in the file, they’re let in. But it doesn’t work the other way around, you can’t work out someone’s password from the hashed version.
IP Blacklisting and IP Whitelisting with .htaccess Permissions
You can use .htaccess file to block users from a specific IP address, or more commonly from an IP range (blacklisting).
You can also do the reverse, blocking everyone out and just allowing certain IP addresses or IP ranges to have access to your site (whitelisting). This is usually used to restrict access to only users from a certain network or area.
Blacklisting by IP
To block specific IP addresses, simply use the following directive, with the appropriate IP addresses that you intend to block:
order allow,deny deny from 22.214.171.124 deny from 789.56.4. allow from all
Notice that in the third line, the last part of the IP address is left empty. That blocks all requests from all IP addresses that start with 789.56.4. – which is called IP range blacklisting.
For whitelisting certain IP addresses or IP ranges, you can block from all and allow only those.
Blocking Users by Referrer through .htaccess Permissions
A referrer is a website that contains a link to a page on your website. When a user clicks on such a link, they navigate from the referrer site to yours. Sometimes this is an unwanted connection, for example, you are linked for the wrong reason or promise, and users coming through that referrer leave your website soon, hurting your success rate.
To do this, you need the mod_rewrite module enabled. This is enabled by default for most web hosts, but if it isn’t or you aren’t sure, you can just contact your hosting company’s support. The .htaccess code to block by referrer looks like this:
RewriteEngine on RewriteCond % ^http://.*example\.com [NC,OR] RewriteCond % ^http://.*anotherexample\.com [NC,OR] RewriteCond % ^http://.*onemoreexample\.com [NC] RewriteRule .* - [F]
The part you would need to change for your own use is the domain name (example) and extension (com).
You may notice that there’s a backslash before .com. That’s because dot character means something in parsing regular expressions (which these lines are) and we want to tell the engine to expect a literal dot character here; therefore, we put an “escape character” (meaning the backslash) before the dot for it to be considered an actual dot.
The parts in the brackets at the end of each line are shortcodes for the RewriteEngine. NC means that the URL is not case-sensitive, OR means that there are more rules to follow, the final F means Forbidden. As a result, the webserver will return a 403 Forbidden status code in answer to requests matching these rules.
Hotlinking is the practice of linking to resources from other domains instead of uploading the content to your own server and serving it yourself. When people hotlink to your files such as images or videos, they’re going to use your resources and bandwidth for free for their own website.
If you are having a problem with hotlinking, you can disable it with some mod_rewrite rules added to your .htaccess file.
RewriteEngine on RewriteCond % !^$ RewriteCond % !^http://(www.)?example.com/.*$ [NC] RewriteRule .(gif|jpg|jpeg|png|js|css)$ - [F] Hiding your .htaccess File: For the Sake of Security
It is very easy to hide your .htaccess file from public view. Just add the following code:
<Files .htaccess> order allow,deny deny from all </Files>
Now, you know what is htaccess file and how to edit it. Although making changes to your .htaccess file can feel great and powerful, but it can also cause serious problems if you do things wrong. There are a few recommendations before you start doing that:
- Do One Thing At a Time
- Backup Your File Before Each Action
- Check the Error Logs
- Use Developer Forums to Get Help