10 ways you can use a .htaccess file on your website

  John Mwaniki /    Updated on 07 Jul 2024

.htaccess (Hypertext Access) file is a directory-level configuration file supported by Apache-based web servers, used for doing various web configurations to the directory in which it is placed and all its subdirectories.

Don't confuse it with a file extension, .htaccess is the actual name of the file. It is a hidden file and that is why its name starts with a dot(.).

How to create a .htaccess file in cPanel

To create a .htaccess file in cPanel, you need first to confirm if it already exists in the directory you want to have it. If it exists, don't create another one, just open it and add your new rules/configurations in it.

Step 1: Log in to your hosting account cPanel.

Step 2: Click on the File Manager icon, located in the Files category.

cPanel File Manager

Step 3: Click Settings in the top right corner of the File Manager.

cPanel file manager settings

Step 4: Check/tick the box for “Show hidden files” and click “Save”.

Showing hidden files in cPale file manager

Now you will be able to see hidden files and folders whose names start with a dot (.).

Now navigate to the directory where you want to have a .htaccess file. If none exist there, click on the “+ File” menu item at the top left of your file manager.

creating a file in cpanel file manager

A popup appears, write the file name as “.htaccess” and click the “Create New File” button.

Creating a .htaccess file in cpanel file manager

You will be able to see it among other files and you can open it to start adding your rules/configurations.

To overwrite the rules in the root .htaccess file (in public_html) for the files in the subdirectories, simply create a new .htaccess file with new rules and place it in the specific subdirectories.

10 configurations you can make using .htaccess file

1. Denying access to a directory

If you have a directory/folder on your website, which you don't want your website visitors to browse and view its contents, just create a file in that directory and name it .htaccess.

In it, write the following line.


Options -Indexes

If anyone tries to access that folder, the browser displays a "403 Forbidden" error message or loads your custom 403 error page if you have already created it.

2. Forcing web pages to HTTPS version

Secure Hypertext Transfer Protocol(HTTPS) is an extension of Hypertext Transfer Protocol(HTTP), used to ensure communication is secure over a computer network, mostly the Internet.

To enforce HTTPS on your website, you first install an SSL certificate on your website(or confirm whether it is already installed). Then force(redirect) all your website traffic(visitors) to access the HTTPS version. You do this URL redirection with the help of the .htaccess file with the lines below:

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

Simply create a file namely .htaccess and place it in the root folder of your website. In most cases, it will be the public_html folder of the cPanel File Manager unless the website is on a subdomain. Then copy and paste the above lines into it.

Note: If there already exists a .htaccess file in the directory, you don't need to create another one. Just add the lines into the existing one. The first line (RewriteEngine On) should only appear once in the file... If it is already there, just copy and paste the other two lines and ensure you place them at a position lower than it (RewriteEngine On).

Using this website as an example, the above commands will redirect you to https://webdesplanet.com (when you try to access webdevsplanet.com or http://webdevsplanet.com) or redirect you to https://www.webdevsplanet.com (when you try to access www.webdevsplanet.com or http://www.webdevsplanet.com).

3. Redirecting to the www version of URLs

When you create your new website, it will be accessible via both www and non-www. ie, your website will be accessible via both yourdomain.com and www.yourdomain.com.

While no version is superior to the other from a technical perspective, it is important to only have one version of the domain name. Choosing one depends on your preference but you should stick with it.

Search engines view yourdomain.com and www.yourdomain.com as totally two different websites. This can raise issues with duplicate content, and negatively affect your website ranking in search engine results.

Choosing one and sticking to it creates more consistency and an authoritative image for search engines and website users.

Using the .htaccess file, you can redirect all your website pages to the www version of the URLs as shown below. Just place the lines below into your website root directory .htaccess file.

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

If you choose to go with the non-www domain version, you can redirect all the traffic/requests with www to it via .htaccess file as below:

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

4. Removing/hiding file extensions from URLs

You've probably visited countless websites whose page URLs don't have file extensions (including this site). Their URLs will be like https://www.webdevsplanet.com/about instead of https://www.webdevsplanet.com/about.php (or the extension of whichever language the page is built on).

Having such URLs has become a standard trend, with most CMS platforms such as WordPress and web development frameworks eg. Laravel all having this type of URL.

Advantages of having such URLs could be:

  • To easily change the back-end technology of the website without affecting the URL eg. changing from .jsp to .php
  • To make URLs look pretty and appealing
  • To hide the back-end programming language of the website from end-users.

For whatever reason you choose to do this, you can easily accomplish it with the help of the .htaccess file. Simply place the commands below in the .htaccess file of your website root folder to remove .php extensions.

RewriteEngine On
RewriteCond %{THE_REQUEST} /([^.]+).php [NC]
RewriteRule ^ /%1 [NC,L,R]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.]+)$ $1.php [NC,L]

To remove the .html extensions from HTML files in URLs, copy-paste the code below into your .htaccess:

RewriteEngine On
RewriteCond %{THE_REQUEST} /([^.]+).html [NC]
RewriteRule ^ /%1 [NC,L,R]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.]+)$ $1.html [NC,L]

5. Displaying custom error pages of your website

There will be some scenarios where web visitors will be served with error responses by your server when trying to access certain pages or files on your website. This could be: when trying to access a page that doesn't exist, when trying to access a file or directory in which they don't have adequate permission, when the page/resource they are trying to access is temporarily down or unavailable, etc.

When such errors occur, the server displays default error pages that are unfriendly to the users and likely to send them out of your website. It is therefore important to create your own custom error pages that are more informative and friendly, in which the website visitors get redirected when such errors occur.

Once you have those pages created, add in the .htaccess, the lines to load the respective errors occur eg as shown below:

ErrorDocument 403 /403.php
ErrorDocument 404 /404.php
ErrorDocument 500 /500.php
ErrorDocument 503 /503.php

6. Enabling browser caching

Caching is the process of downloading static website files, such as HTML documents, media files, images, CSS, and JavaScript files and temporarily storing them on a visitor’s device’s storage.

This enables their web browser to load these files directly from their local storage without having to request them from the server when these visitors return to the website again.

This incredibly increases the website loading speed thus increasing its user experience and also affecting the site ranking in Google. The shorter the website takes to load, the better.

To set up browser caching on your server, add the following lines in your .htaccess file(you can change the values to your preferred duration):

# BEGIN EXPIRES
ExpiresActive On
ExpiresDefault “access plus 10 days”
ExpiresByType text/css “access plus 1 week”
ExpiresByType text/plain “access plus 1 month”
ExpiresByType image/gif “access plus 1 month”
ExpiresByType image/png “access plus 1 month”
ExpiresByType image/jpeg “access plus 1 month”
ExpiresByType application/x-javascript “access plus 1 month”
ExpiresByType application/javascript “access plus 1 week”
ExpiresByType application/x-icon “access plus 1 year”
# END EXPIRES

7. Compressing website files

The smaller your website files are, the faster your website pages will load. You can achieve this by minifying your files, doing away with unnecessary bloated codes, or by compressing your website files.

You can compress these files using Gzip compression and reduce their sizes by up to 70% which will greatly increase your website speed. To enable Gzip compression, simply add the following lines into your .htaccess file.

# compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
# Or, compress certain file types by extension:
SetOutputFilter DEFLATE
# END EXPIRES

8. Blocking certain IP addresses from accessing the website

You may for some reason want to block some IP addresses from accessing your website. This could be an IP address of a person who has been repeatedly trying to hack your website, a spammer in your forums or blog comments, site scrapers, etc.

To block a specific IP address, just use the command below in your .htaccess file.

Deny from xxx.xxx.xxx.xxx

Just replace xxx.xxx.xxx.xxx with the IP address you want to block.

You can also block multiple IP addresses all at once by writing them all separated by spaces as shown below:

Deny from xxx.xxx.xxx.xxx yyy.yyy.yyy.yyy zzz.zzz.zzz.zzz

9. Preventing your images from hotlinking

Hotlinking is a practice where websites directly link to files (eg images, css, js etc) on another website. For example, if a file namely image1.jpg exists in a directory "https://www.webdevsplanet.com/images/", someone may add it in "https://www.webdevsplanet.com/images/image1.jpg" their HTML image SRC attribute.

By doing that, the other site will be stealing your bandwidth and may slow your site down.

To prevent your images from being hotlinked, you can add the following lines to your .htaccess file. Replace example.com on line 3 with your own domain name.

RewriteEngine on 
RewriteCond %{HTTP_REFERER} !^$ 
RewriteCond %{HTTP_REFERER} !^http(s)?://(www.)?example.com [NC] 
RewriteRule .(jpg|jpeg|png|gif)$ – [NC,F,L]

10. Adding HTTP security headers to your website

HTTP security headers are a subset of HTTP headers, exchanged between the web browser and server to specify the security-related details of HTTP communication.

By enabling these headers in your web applications and web server settings, you can secure your web application against many common attacks, including cross-site scripting (XSS) and clickjacking.

Below are must-have headers on your website if you care about its security:

HTTP Strict Transport Security (HSTS)
This header forces the browser to communicate over secure HTTPS. This should be set up only if you have an SSL certificate installed on your website. It's especially important if you have not redirected your website URLs to the HTTPS version. It eliminates the possibility of an HTTP connection entirely.

Cross-Site Scripting Protection (X-XSS)
This header as its name suggests protects the website against Cross-Site Scripting attacks. It filters the requests and prevents the page from loading when it detects a cross-site scripting attack.

X-Frame-Options
This header prevents your website from being embedded in iframes on other websites. Using SAMEORIGIN ensures that your site/page can only be embedded in another page within your domain name.

X-Content-Type-Options
This header protects your website against MIME sniffing, a feature used to discover an asset’s file format. MIME sniffing can also be used to execute cross-site scripting attacks.

Adding the lines below in your .htaccess file sets up all the above four security headers and improves your website security.

Header set Strict-Transport-Security "max-age=31536000" env=HTTPS
Header set X-XSS-Protection "1; mode=block"
Header always append X-Frame-Options SAMEORIGIN
Header set X-Content-Type-Options nosniff

Conclusion

Hypertext Access (.htaccess) file is very important in enabling web developers to do configurations on Apache-based web servers.

In this article, we have covered what a .htaccess file is, how to create it, and 10 different ways in which you can use it to do configurations on your web server.