The Basics of the .htaccess File
.htaccess is a hidden configuration file that lets you configure various features of the Apache web server, on a per-directory basis. This includes redirecting URLs, caching, enabling HTTPS, hotlink protection, and setting up custom error pages.
The configuration directives defined in a .htaccess file apply to the directory, and all its subdirectories. This allows you to customise the Apache server’s behaviour for different directories. These files have the same syntax as the main Apache configuration files.
As per the official Apache documentation, you should only use .htaccess files if you don’t have access to the main configuration file (e.g. when using a shared host). This is because most, if not all, of the configuration directives, work better when defined in the main configuration file.
Where to find the .htaccess file
To find your .htaccess file on cPanel, follow these steps:
Log in to your cPanel account.
Click the File Manager icon under Files
Click the Settings icon on the top right, and then select the Show Hidden Files (dotfiles) and click Save.
Scroll down to your public_html folder and double-click it to check inside for the .htaccess file.
If you don’t find it there, you’ll have to create one.
How to create a .htaccess file and add code to it
If you couldn’t locate the .htaccess file through the steps shown above, it’s likely that you don’t have it.
To create a new file
- Log in to your cPanel account.
- Click the File Manager icon under Files.
- Click the Settings icon on the top right, and then check the Show hidden files checkbox.
- Open your public_html folder.
- Once inside your public_html folder, click the +File icon in the top-left corner.
- Type .htaccess as the name of the file, and click Create New File
To add code
To edit the file and/or add code to it, right-click it and select Edit.
You will be prompted to enable/disable Encoding Check and select a character encoding for the file. Unless you know what you’re doing, ignore the prompt and click Edit.
A file editor should open. Copy the code you want to add and paste it inside the text space.
Once you’re done adding code, click Save Changes and Close.
What can I do with the .htaccess file?
There is a multitude of cool features that you can implement via a .htaccess file. Let’s look at a few:
Display custom error pages
Visitors hate errors. They hate them less when the error page tells them exactly what’s wrong, in a user-friendly way. Using a .htaccess file, you can define a custom error page for every HTTP error code that your server produces. For example, the following line of code will display a page called 400.html, present inside the errors directory.
ErrorDocument 400 /errors/400.html
Protect your directories with a password
To enhance your website’s security, it’s recommended to protect sensitive directories with a password. To achieve this, you’ll need to generate a file known as .htpasswd. Here are the steps:
- Navigate to the directory which you want to password-protect.
- Use the
pwd
command to get the full path of the directory. - Use the following command to generate a .htpasswd file, using the
htpasswd
utility.
htpasswd -c /var/www/website-url.com/public_html/.htpasswd username
Alternatively, you can also use an online htpasswd generator to generate the file.
- When prompted, enter a password for the user
username
. - Finally, put the following code inside your .htaccess file:
AuthType Basic AuthName “Password protection” AuthUserFile /var/www/website-url.com/public_html/.htpasswd Require valid-user
Blacklist and whitelist IPs and domains
.htaccess files also allow you to set up different blacklisting and whitelisting rules.
For example:
To deny incoming traffic from all except whitelisted:
Order deny, allow Deny from all Allow from 192.101.145.23 localhost
To deny traffic from an IP:
Deny from 192.168.121.23
To block access to only PHP files:
<Files ~ "\.php$"> Order allow,deny Deny from all </Files>
To block a domain:
SetEnvIfNoCase Referer "blockeddomain.com" blocked_domain Order Allow,Deny Allow from ALL Deny from env=blocked_domain
The above lines of code will display a 403 Forbidden error to any user who accesses your website from the blocked_domain
.
Block bots
Some bots are malicious users or tools that bombard your website with large amounts of unwanted traffic.
You can usually identify bots by the user-agent attribute of the HTTP request header.
To block bots from sending traffic to your website, you can define a RewriteRule
directive in your .htaccess file.
For example, the following line will block the ChinaClaw
bot.
RewriteEngine On RewriteCond %{HTTP_USER_AGENT} ChinaClaw [NC] RewriteRule .* - [F,L]
To block multiple bots or site rippers, use the following syntax:
RewriteEngine On RewriteCond %{HTTP_USER_AGENT} ^BlackWidow [OR] RewriteCond %{HTTP_USER_AGENT} ^Bot\ mailto:craftbot@yahoo.com [OR] RewriteCond %{HTTP_USER_AGENT} ^ChinaClaw [OR] RewriteCond %{HTTP_USER_AGENT} ^Custo [OR] RewriteCond %{HTTP_USER_AGENT} ^DISCo [OR] RewriteCond %{HTTP_USER_AGENT} ^Website\ Quester [OR] RewriteCond %{HTTP_USER_AGENT} ^Widow [OR] RewriteCond %{HTTP_USER_AGENT} ^WWWOFFLE [OR] RewriteCond %{HTTP_USER_AGENT} ^Xaldon\ WebSpider [OR] RewriteCond %{HTTP_USER_AGENT} ^Zeus RewriteRule ^.* - [F,L]
Implement URL rewrites
Using the mod_rewrite
directive, you can rewrite URLs on the fly. You can map a URL to a path on the file system, or to another URL. Let’s look at a few examples:
The following lines of code will redirect http://website.com/file.html to http://website.com/directory1/
file.html:
Options +FollowSymLinks RewriteEngine On RewriteCond %{HTTP_HOST} website.com$ [NC] RewriteCond %{HTTP_HOST} !directory1 RewriteRule ^(.*)$ http://website.com/directory1/$1 [R=301,L]
To add www
to a URL, use the following code:
Options +FollowSymLinks RewriteEngine on RewriteCond %{HTTP_HOST} ^website.com [NC] RewriteRule ^(.*)$ http://www.website.com/$1 [R=301,L]
This code will transform http://website.com to http://www
.website.com.
You can also convert HTTP requests to HTTPS using the following code:
RewriteEngine On RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://www.website.com/$1 [R,L]
Implement URL redirects
The Redirect
directive allows you to redirect a directory to another directory, a directory to an HTML file, a URL to another URL, and so much more.
To redirect from one URL to another:
Redirect 301 /var/usr/project.html http://www.website.org/newpage.html
To redirect from index.html to custom-index.html:
Redirect /index.html /custom-index.html
To load a .gif file from another website:
Redirect /asset/main.gif https://www.website.com/asset/main.gif
Set a default directory index
The default index page of a directory is always index.html. To define a different directory index, you can use the following command:
DirectoryIndex myindex.html
You can even define multiple files, in which case the web server looks for each file until it gets a match.
DirectoryIndex index.html index.php myindex.html
Deny directory listing
To deny directory listing, you can add the following line to your .htaccess file:
Options –Indexes
Add MIME types
Add a MIME type to your server by using the following .htaccess code:
AddType text/html .html .htm
…where text/html
is the MIME type, and .html
and .htm
are the supported extensions.
Enable hotlink protection
Hotlinking happens when other websites link directly to assets on your server, like images or videos, etc. This can be detrimental to your website’s performance, as others are consuming your bandwidth, as well as storage space. Fortunately, .htaccess provides an easy way to prevent hotlinking.
Add the following code to completely disable hotlinking. Remember to replace website.com
with your own domain.
RewriteEngine on RewriteCond %{HTTP_REFERER} !^$ RewriteCond %{HTTP_REFERER} !^http://(www\.)website.com/.*$ [NC] RewriteRule \.(gif|jpg|jpeg|bmp|zip|rar|mp3|flv|swf|xml|php|png|css|pdf)$ - [F]
Set up browser caching
The mod_expires
directive instructs browsers to cache certain files, i.e. hold on to them for subsequent visits.
For example, the following code sets the default expiry time as access plus 1 seconds
, and then sets access plus 2592000 seconds
as the expiry for the specified multimedia file types.
# BEGIN Expire headers <IfModule mod_expires.c> # Turn on the module. ExpiresActive on # Set the default expiry times. ExpiresDefault "access plus 1 seconds" ExpiresByType image/jpg "access plus 2592000 seconds" ExpiresByType image/png "access plus 2592000 seconds" ExpiresByType image/gif "access plus 2592000 seconds" ExpiresByType image/ico "access plus 2592000 seconds" </IfModule> # END Expire headers
Add security headers to your website
You can use security headers to increase your website’s security, and let browsers know which client-side features are allowed.
Here’s how to add security headers to your .htaccess file:
<IfModule mod_headers.c> Header set Content-Security-Policy "upgrade-insecure-requests" Header set Strict-Transport-Security "max-age=31536000; includeSubDomains" Header set X-Xss-Protection "1; mode=block" Header set X-Frame-Options "SAMEORIGIN" Header set X-Content-Type-Options "nosniff" Header set Referrer-Policy "strict-origin-when-cross-origin" Header set Permissions-Policy "geolocation=self" </IfModule>
Tweak PHP settings
You can even adjust PHP settings through the .htaccess file.
Here’s the format:
php_value conf_name conf_value
Some examples:
php_value upload_max_filesize 5M
php_value post_max_size 20M
php_value max_execution_time 60
Conclusion
The .htaccess file simplifies the process of managing and configuring a website. In this article, we talked about some of the most beneficial features you can implement with it.
To explore more, go through the official Apache documentation.