What is .htaccess?
The .htaccess (Hypertext Access) file is a directory-level configuration file supported by several web servers - particularly the Apache Web Server.
It is used to manage the server's settings without needing to modify the server's global configuration files.
This file is placed in a specific directory on the server and it then applies various rules to that directory and its subdirectories. It allows the configuration of website elements without altering server core files.
Functions of a .htaccess file can include redirecting URLs, rewriting URLs, restricting access to certain parts of the website and managing cache control.
It is a powerful tool but it needs to be used with caution because incorrect configurations can lead to issues like server errors and accessibility problems.
The format of .htaccess
The .htaccess file is a plain text file that uses a specific syntax to give instructions to the server. The syntax of .htaccess is directive-based. That means it consists of directives each of which applies a particular server setting or behaviour.
Here is a very basic example of what the contents of a .htaccess file might look like:
# Turn on rewrite engine
RewriteEngine On
# Redirect from old page to new page
Redirect 301 /oldpage.html /newpage.html
In this example:
The # character is used to start a comment. Anything after this character on the same line is ignored by the server.
The RewriteEngine On directive turns on the Apache mod_rewrite module which allows for URL manipulation.
The Redirect 301 /oldpage.html /newpage.html directive tells the server to issue a 301 (permanent) redirect from oldpage.html to newpage.html.
A more complex .htaccess file might include additional directives for tasks such as password protection, error document handling and many more.
What is .htaccess used for?
A .htaccess file is used for multiple purposes:
URL Rewriting
One of the most common uses of .htaccess is for URL rewriting. It is usually done in conjunction with mod_rewrite - a module that allows for rewriting URLs. This is heavily used in creating SEO-friendly URLs or to create clean URLs.
Redirects
.htaccess can handle website redirects. For instance, if a page's location has changed, .htaccess can automatically redirect the user from the old location to the new one.
Make use of our .htaccess code generator tool for effortless setup of redirects.
Password Protection
You can use .htaccess to protect directories on the server with a password. This means when a user attempts to access that directory via the browser, they are prompted for a username and password.
To simplify the process, you can use our .htaccess code generator tool to easily implement password protection for your files.
Custom Error Pages
.htaccess can be used to specify custom error pages for different server errors. For example, you can set a specific page to display when a 404 error (page not found) occurs.
To easily create custom error pages for your website, you can utilize our .htaccess code generator tool for seamless integration.
Deny/Allow certain IP Addresses
.htaccess can also be used to restrict or grant access to certain parts of your website based on IP addresses.
Here you can simplify the process of restricting or granting access to specific IP addresses using our Deny/Allow IP Addresses feature and effortlessly generate the code for it.
Disable Directory Browsing
By default, when there is no index file in a directory, the server will display a list of all files in that directory. With .htaccess directory browsing can be turned off.
File Caching
You can use .htaccess to control the caching of your site content in users' browsers which can speed up the loading of your site for returning visitors.
Don’t know how to do this? Use our Cache Assets feature in the .htaccess generator tool. Add the required details and easily create code for your website.
Where is the .htaccess file located?
The .htaccess file is typically found in the root directory of your website. It is often named as public_html. It can also be placed in any other directory to specifically affect that directory and its subdirectories.
If you are having trouble finding it, remember the .htaccess file is a hidden file - identifiable by the "." at the beginning of its name.
This means you might need to adjust the settings of your file manager or FTP client to show hidden files.
For instance, if you are using an FTP client like FileZilla, navigate to the “Server” menu and select the “Force showing hidden files” option.
Similarly, in cPanel's File Manager, click on the “Settings” button at the top right. Check the box for “Show Hidden Files”, and hit “Save”.
Your .htaccess file should become visible by following these steps if it exists in the directory you are currently viewing.
If you still can't locate it, it is possible that one has not been created for your site yet. In that case, you can create a new one using a text editor and upload it to the necessary directory.
However, exercise caution while creating or editing the .htaccess file as mistakes can lead to website errors.
How to create a .htaccess file?
Creating a .htaccess file is fairly straightforward. Here is how you can do it:
Open a text editor
Use any text editor like Notepad on Windows or TextEdit on MacOS. If you are using TextEdit, make sure it is in plain text mode. You can switch to this mode by clicking “Format” in the top menu and then “Make Plain Text”.
Enter your directives
The .htaccess file works by specifying certain directives or commands that the server will follow. You write these out in text form.
For example, to enable a 301 redirect from an old page to a new one, you would write Redirect 301 /oldpage.html /newpage.html.
Save the file
When you are done writing out your directives, save the file. Make sure to name it .htaccess. The name should start with a dot and follow by htaccess with no file extension at the end.
Upload the file
Once you have saved the file, upload it to your server. It should go in the root directory of your website or in the directory of the specific site section you want to affect.
Caution: Remember the .htaccess file is very powerful and a small mistake can potentially take your site offline. Always make sure to back up your existing .htaccess file before making changes and test thoroughly after the changes have been made.
Make sure that your web server supports .htaccess-style directives - not all do. This method is specific to Apache servers and servers using the NGINX architecture won't support this method.
How .htaccess is helpful in SEO?
The .htaccess file can significantly impact the SEO of your website in several ways:
URL Redirection
.htaccess can be used to set up 301 redirects, which are necessary when a page URL changes. Instead of landing on a 404 error page, visitors or search engine bots are automatically redirected to the new page.
This is crucial for SEO as it ensures the continuity of any link equity the original page had accumulated.
In other words, any “credit” the old page had earned in terms of its search ranking is transferred to the new page.
Here is an example of how to set this up:
Redirect 301 /old-page.html /new-page.html
In this example, if someone tries to access http://yourwebsite.com/old-page.html, they will be automatically redirected to http://yourwebsite.com/new-page.html.
If you want to avoid mishandling of code, you can generate it by using our 301 Redirect File or Directory feature in the .htaccess code generator.
URL Rewriting
You can use .htaccess to create clean and easy-to-read URLs. This not only makes your website easier to navigate for users but also makes your URLs more appealing to search engines which can enhance your site's SEO.
You can use the mod_rewrite module in the .htaccess file to transform dynamic URLs into cleaner static URLs. Here is an example:
RewriteEngine On
RewriteRule ^product/([0-9]+)/?$ product.php?id=$1 [NC,L]
In this example, a URL like http://yourwebsite.com/product.php?id=123 will be rewritten to appear as http://yourwebsite.com/product/123.
The ^product/([0-9]+)/?$ pattern matches any URL that starts with "product/" followed by one or more numbers.
The ( ) creates a group and $1 refers to the contents of that group. [NC,L] makes the rule case-insensitive and signals that no other rules should be processed if this one is applied.
Canonicalization
To avoid duplicate content issues, you can enforce a preferred domain (with or without 'www') using .htaccess.
For example, to redirect all http://yourwebsite.com URLs to http://www.yourwebsite.com you can use:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^yourwebsite\.com [NC]
RewriteRule ^(.*)$ http://www.yourwebsite.com/$1 [L,R=301]
This verifies whether the accessed host is “yourwebsite.com” and if it is, it modifies the URL to attach “www.” at the beginning.
We have ensured convenience for our users by providing an easy way to generate code for redirecting from www to non-www and non-www to www in our .htaccess code generator. This will help you effortlessly generate the necessary code to prevent any mishandling.
Preventing Hotlinking
Hotlinking refers to the practice where other websites embed your content such as images, videos or other types of files on their own site by linking directly to the file URL on your server.
This means they're effectively using your server resources to display the content which can slow down your site and impact its performance.
You can prevent hotlinking by using .htaccess as follows:
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourwebsite.com [NC]
RewriteRule \.(jpg|jpeg|png|gif|pdf|mp3|mp4)$ - [NC,F,L]
This code block will prevent any website that is not “yourwebsite.com” from using files stored on your server.
In this example, the file types specified are images (jpg, jpeg, png, gif), PDF documents (pdf) and audio and video files (mp3, mp4). You can modify this list as needed to include other file types that are relevant to your site.
There is another quick and easy way to generate code for this purpose. You can access our Prevent Hotlinking tool, enter the required details and easily create code for your website.
Setting up a Custom 404 Page
Having a user-friendly 404 error page can help keep users on your site even if they encounter a broken link. You can set this up in your .htaccess file:
ErrorDocument 404 /404.html
Here when a visitor tries to access a non-existing page, they will be redirected to 404.html which is your custom 404 error page.
Ensure that this page provides useful information and navigation options to keep the users engaged.
Force HTTPS
If you want to ensure that all traffic to your website uses HTTPS, you can do this by adding some rules to your .htaccess file or alternatively use our tool HTTP vs HTTPS URL Redirects for this purpose.
The code snippet would look something like this:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
This set of rules forces your website to use HTTPS instead of HTTP which is beneficial in many ways including improved website security and potentially better search engine ranking.
Force URL to www
To force your website to always use “www” in the URL, you can add the following rules to your .htaccess file:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^yourdomain.com [NC]
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [L,R=301]
Replace "yourdomain.com" with your actual domain name.
This set of rules will ensure that users always access your website with "www" in the URL which can be beneficial for SEO by avoiding duplicate content issues between the www and non-www versions of your site.
Alternatively, you may use our tool to redirect non-www URLs to www.
Compressing Files with Gzip
Compressing your site's files can reduce their size, resulting in faster load times and a better user experience, which is good for SEO.
You can enable Gzip compression with this code:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE image/x-icon
AddOutputFilterByType DEFLATE image/svg+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/x-font
AddOutputFilterByType DEFLATE application/x-font-truetype
AddOutputFilterByType DEFLATE application/x-font-ttf
AddOutputFilterByType DEFLATE application/x-font-otf
AddOutputFilterByType DEFLATE application/x-font-opentype
AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
AddOutputFilterByType DEFLATE font/ttf
AddOutputFilterByType DEFLATE font/otf
AddOutputFilterByType DEFLATE font/opentype
</IfModule>
This snippet checks if the mod_deflate module is enabled - a module that handles compression in Apache servers - and if so, it applies compression to the file types listed.
Pros and cons of .htaccess
.htaccess has the following pros and cons:
Pros
Offers versatile management by interpreting all incoming requests.
Changes take effect immediately which eliminates the need for server restarts.
Enables user access control based on individual preferences.
Allows the setting of directory-level configurations for more granular control.
Acts as a beneficial tool for search engine optimization by aiding in URL rewriting, redirect management etc.
Cons
Can introduce potential security vulnerabilities if not managed correctly.
Operates slower than server-level configurations as it must be read every time a page is loaded. This could negatively impact website performance, especially for high-traffic sites.
It might not be the preferred method for server configuration due to potential security and performance issues.
Common errors you may get after updating the .htaccess file
Editing or updating the .htaccess file can sometimes lead to errors if not done correctly.
Following are some common error messages that may arise after an update:
500 Internal Server Error: This is a generic server error and often occurs when there's a problem with the .htaccess file itself such as incorrect syntax or unsupported directives.
403 Forbidden Error: This error might show up if permissions are incorrectly set via the .htaccess file or if the file is instructing the server to deny access to a particular resource.
404 Not Found Error: If rewrite rules in the .htaccess file are misconfigured it might lead to broken links.
406 Not Acceptable Error: This error may occur if mod_security (an application firewall) rules in the .htaccess file are improperly configured.
500 Internal Server Error error was encountered while trying to use an ErrorDocument…: This error can show up when the server is instructed to display a custom error page that doesn't exist or is unreachable.
When dealing with these errors, here are some troubleshooting steps to consider:
Check for Syntax Errors: The most common reason for .htaccess errors is incorrect syntax. Ensure that all directives are written correctly and that you have closed all brackets. For instance, each RewriteCond directive should be followed by a RewriteRule.
Examine Permissions: Make sure that the file permissions for .htaccess are set correctly. Typically, .htaccess should have 644 permissions, read and write permissions for the user and read permissions for the group and others.
Disable Directives: Try commenting out sections of your .htaccess file to isolate the problem. You can do this by adding a # at the beginning of each line which will make the server ignore that directive. Start from the bottom and work your way up - commenting out one section at a time and then checking your website.
Check with Hosting Provider: Some hosting providers do not allow certain directives in .htaccess files. If you are unable to resolve the problem yourself reach out to your hosting provider's support team for assistance. They may be able to spot issues that you missed or explain if certain directives are not allowed on their servers.
Use Online Tools: There are online tools that can help you validate the syntax of your .htaccess file. If you suspect a syntax issue, copying and pasting your content into one of these validators could help identify the problem.
Remember, always keep a backup of your .htaccess file before making any changes. This way if anything goes wrong you can easily revert back to the previous state.
Also, make small changes one at a time and check your site after each change so that if something does break, you will know exactly what caused it.
Takeaway
The .htaccess file controls server behaviour and various website features. It is crucial for tasks like URL redirection, canonicalization, security and more.
This hidden file usually resides in the root directory of your website and requires careful editing to avoid website malfunctions. So it is recommended to always back up the .htaccess file before making any changes.
For a seamless experience in generating .htaccess code for various configurations, make use of our .htaccess code generator tool.