As we know, .htaccess is a small but powerful plain text file that you can use to make configuration changes to Apache on a per-directory basis. It acts as a middleman between you and the Apache web server.
Learn to modify the .htaccess file, and you’ll have the power to direct your users to the right page, enhance security, and tweak your site’s performance.
By modifying the .htaccess file, you can change the behavior of your website in ways that would otherwise require higher access levels than your hosting account may offer. This .htaccess tutorial will explain how to harness the power of .htaccess to accomplish common tasks.
Some of the capabilities it offers include:
- URL redirection and rewriting — Ensure your users reach exactly where you want them to go.
- Security — Restrict access to particular files or directories or block unwanted access to your site.
- Site optimization — Implement tweaks that enhance site performance.
Now let’s dive into our .htaccess tutorial.
Placing the .htaccess file
An .htaccess file is most often located in the root of the website it controls. From there, it will affect all subfolders within the site.
However, you can also place an .htaccess file in a specific subdirectory deeper in your site’s structure.
This is useful if you only want to affect a portion of your website, as the file will only impact the directory it’s in and those beneath it.
It is permissible to have multiple .htaccess files on a site, though for ease of maintenance, webmasters often use a single file located in the site root to make all necessary changes.
Performance considerations when using .htaccess
While .htaccess files offer great flexibility, they can have performance implications on your server. Each time a request is made, the server searches for and processes an .htaccess file in the requested directory and all parent directories.
This per-directory processing can slow down server response times, especially if there are multiple .htaccess files scattered throughout your site’s directory structure.
Here’s how to optimize performance:
Use the main server configuration file
Whenever possible, implement redirects and configurations directly in the main server configuration file (e.g., httpd.conf) instead of using multiple .htaccess files.
The main configuration file is loaded once when the server starts, reducing the overhead associated with per-request processing.
Minimize the number of .htaccess files
Consolidate your configurations into a single .htaccess file located in the root directory. This minimizes the number of file checks and processing steps the server must perform for each request, thereby improving overall server speed and efficiency.
Additionally, effective redirect management plays a crucial role in optimizing site performance and enhancing Core Web Vitals.
By minimizing redirect chains and ensuring that redirects are as efficient as possible, you can reduce page load times, which directly impacts metrics such as Largest Contentful Paint (LCP) and First Input Delay (FID).
Proper redirect configurations also support mobile-first indexing by ensuring that mobile users are swiftly directed to the appropriate content without unnecessary delays. This contributes to a smoother user experience on mobile devices, which is a key factor in mobile-first indexing strategies.
By following these recommendations, you can enhance your website’s performance and ensure faster load times for your users.
Editing .htaccess from cPanel
Any text editor can be used to modify .htaccess, including the one built into cPanel’s File Manager. It’s a convenient way to edit .htaccess files.
- Log into cPanel.
- Under the Files section, click on the File Manager icon.
- In the popup window, select the Document Root for the site you are working on and make sure Show Hidden Files is checked. Note that some versions of File Manager may have a slightly different interface but will require the same setting selections. If the window below doesn’t pop up automatically when you click on File Manager, look for a Settings icon and click on that to reach these settings.
- Look for the .htaccess file and right-click on it. From the drop-down menu that appears, select Edit.
- You will now be in the text editor, where you can make and save changes.
Related: cPanel tips and tricks that will make your life easier
Don’t forget to create a backup
If you mess up your .htaccess file you can easily break your website, so create a backup first. If you do crash your website and for some reason don’t have a backup, don’t panic — simply rename .htaccess to .htaccess.old and that should bring it back up.
What’s the dot at the beginning of the filename for?
The dot at the beginning of the file name tells Unix/Linux systems to hide this file, so when using file manager, be sure to tick the checkbox for “show hidden files” or you might not be able to find it.
Manage redirects with .htaccess
Redirects are essential for directing users and search engines to the correct URLs, ensuring a seamless user experience and preserving SEO value. Here’s how to manage them effectively using your .htaccess file.
Understanding redirect status codes
There are several redirect status codes you can use, each serving a different purpose:
301 redirects (moved permanently)
Indicates that a page has been permanently moved to a new URL. This is the best type for SEO as it transfers the ranking authority to the new page.
Example: Redirect 301 /oldpage/ https://www.example.com/newpage/
302 redirects (found & moved temporarily)
Used for temporary redirects, such as during site maintenance or A/B testing. Note that this does not transfer SEO authority to the new page.
Example: Redirect 302 /temporary-page/ https://www.example.com/new-temporary-page/
303 redirects (see other)
Directs users to a different page, typically after form submissions to prevent duplicate submissions.
307 redirects (temporary redirect)
Similar to 302 but adheres strictly to the HTTP/1.1 standard, ensuring that the request method does not change.
308 redirects (permanent redirect)
Similar to 301 but also ensures that the request method remains the same. These are less commonly used but can be useful in specific scenarios.
Best practices for implementing redirects
To maintain both user experience and SEO benefits, follow these best practices when managing redirects:
Maintain relevance
Ensure that the new URL closely matches the content and intent of the old URL to satisfy user expectations and preserve SEO rankings.
Avoid redirect chains and loops
Redirect chains occur when multiple redirects point from one URL to another in a sequence, which can dilute SEO value and slow down page load times.
Redirect loops happen when URLs redirect to each other indefinitely, causing errors. To prevent this, always redirect directly from the original URL to the final destination.
Keep 301 redirects for at least a year
As recommended by Google, maintain 301 redirects for a minimum of one year to ensure that search engines have adequately processed the change and transferred the SEO authority.
Test redirects effectively
After setting up redirects, verify that they work correctly by entering the old URL in a browser and ensuring it redirects to the new URL without errors. Tools like Site Audit can help identify any issues with redirects.
Prevent duplicate content issues
Use redirects to consolidate duplicate pages, directing them to a single, authoritative URL. This helps avoid splitting SEO value and confusing search engines.
Update internal links
Instead of linking to the old URL within your website, update all internal links to point directly to the new URLs. This minimizes the need for redirects and enhances site performance.
Enhance user experience and accessibility
Properly implemented redirects ensure that users have a smooth navigation experience, avoiding broken links and dead ends.
This is crucial for maintaining accessibility compliance, such as adhering to WCAG standards. By directing users seamlessly to the correct pages, you improve usability for all visitors, including those using assistive technologies.
Optimize for Core Web Vitals
Efficient redirect implementations contribute to better Core Web Vitals by reducing unnecessary redirects that can slow down page loads. Ensuring that redirects are minimal and direct helps maintain optimal load times and user interactivity metrics.
Support mobile-first indexing
Streamline redirect paths to ensure that mobile users are quickly and efficiently directed to the appropriate content. Efficient redirects enhance the mobile user experience, which is a key consideration in mobile-first indexing.
Implementing redirects in .htaccess
You can set up various types of redirects by editing your .htaccess file. Here are some common examples:
Redirect a single URL
Redirect 301 /oldpage/ https://www.example.com/newpage/
Redirect an entire domain
RewriteEngine on
RewriteCond %{HTTP_HOST} ^OldDomain\.com
RewriteRule ^(.*)$ https://NewDomain.com/$1 [R=301,L]
Redirect non-WWW to WWW
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]`
Redirect HTTP to HTTPS
RewriteEngine on
RewriteCond %{https} off
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
Improving security using .htaccess
.htaccess can be used to protect single files or an entire directory by denying access entirely or requiring a password. You can also block those sneaky hotlinkers and keep them from using your bandwidth.
Password protect a single file
To password protect a single file in an otherwise public folder, first you need to create an .htpasswd file containing the user name and encrypted password for permitted logins.
An easy way to do this is using a free webmaster tool like the one at 4WebHelp. Once you save the .htpasswd file to your system, you can use .htaccess in conjunction with it. Here’s the complete process:
- Use a webmaster tool to create a username:encrypted_password combo. The line produced will look something like this: User_Name:14fcYjcLcsbMU Copy the resulting line and save it to a text editor.
- Log in to cPanel, and under the Files section, click File Manager.
- In the popup window, select the Home Directory and ensure that Show Hidden Files is selected. This is where you will put the .htpasswd file. This location is hidden from the public and isn’t accessible via a URL, so it is more secure.
- You are now in your home directory. Click the +File link in the top left corner to create a new file there. In the popup window, enter .htpasswd as the file name and click Create New File. Leave the second line blank. It will default to the current, home directory.
- A directory listing of your home directory will be displayed. Note the path displayed in the left-hand pane of file manager as you will need it later. It will be something like /home/username. Scroll down until you find the file you just created and right click on it. (If you don’t see any files beginning with a dot, you probably didn’t select “show hidden files” — you can correct this by clicking on the settings icon and doing it there.)
- The file editor will open. Paste the line you saved from the password encrypter into the new file and save it. You are then ready to move on to the .htaccess modifications.
- Add the following to your .htaccess file using the procedure described at the beginning of this article. Replace /home/username with the path you noted earlier.
- Replace mypage.html with the name of the page you want to password protect. You can also change “Login Required” to something different, like “Members Area” — this will be displayed on the login prompt.
AuthUserFile /home/username/.htpasswd
AuthName "Login Required"
AuthType basic
<Files mypage.html>
Require valid-user
</Files>
- Click Save Changes. Then visit your site and try to access the file to verify the protection is working. If you visit the page a second time, you might not be prompted for the login as your browser will likely remember it.
Related: How to use Bing Webmaster Tools to improve your site’s SEO
Password protect a directory
The procedure to password protect an entire directory is similar to that for protecting a file:
- Create an .htpasswd file as described in the item above, Password protect a single file. Stop after step 6, before making any changes to .htaccess.
- Create a new .htaccess file inside the subdirectory you want to protect and add the following lines:
AuthUserFile /home/username/.htpasswd
AuthName "Login Required"
AuthType basic
Require valid-user
Note that you can also protect a directory via cPanel, without using .htaccess.
Deny access to a single file
To prevent all users from accessing a particular file, add the following lines, replacing the filename with the name of the file you want to protect:
<files filename>
order allow,deny
deny from all
</files>
Deny access to hidden files and directories
Use this to prevent hackers from directly accessing files that should remain hidden — i.e. those that begin with a dot. These lines will give the hacker a 404 not found error rather than an access denied, so the hacker will have no clue.
RedirectMatch 404 /\..*$
Block image hotlinking
Keep people from stealing your bandwidth by linking to your images:
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]
You can also modify the above to show an alternate image instead of the one that’s hotlinked, typically one that says something like “No hotlinking allowed!” To do so, change the last line to this:
RewriteRule \.(jpg|jpeg|png|gif)$ http://www.yourdomain.com/no-hotlinking.jpg [R,L]
Site optimization using .htaccess
Next up in our .htaccess tutorial: Using .htaccess to improve site performance. With it, you can enable file compression and exert some control over caching, which can substantially speed up your site.
Compress text files using gzip/deflate
The Apache mod_deflate module can compress data using gzip compression before transmitting it to the user.
This can reduce the amount of bandwidth your site uses, although it won’t necessarily speed up your site.
The module is already enabled on most servers, but you’ll need to add the line below to actually use it:
AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript
Set expires headers
Browser caching speeds up your website significantly. In order to capitalize on this, you have to set an expiration date for each type of file you want cached. Use the below code as a starting point. You can set the duration of the cache for each item using all the standard time units, including years, months, weeks, days, hours, minutes and seconds.
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
Limit file upload size
To prevent users from uploading massive, resource-hogging files, limit the file upload size using .htaccess. Enter the size limit in bytes.
LimitRequestBody 1048576
Miscellaneous
Here are a few more handy things you can do with .htaccess:
Change default index page
By default, your server will attempt to display index.htm, then index.html, then index.php, and then default.htm as the first page of your website. You can override this to set a default index page as follows (replace first.html with the page you want displayed):
#Set default index page
DirectoryIndex first.html
You can add an entire list here, also, which the server will go through in order until it finds one it can serve up.
#Set default index pages
DirectoryIndex index.php index.htm index.html home.html
Change server time zone
Set your server time zone to anything you’d like. The code below sets the server to New York time. A handy list of time zones is located here.
#Set server time zone
SetEnv TZ America/New_York
Custom error messages and pages
It’s very easy to change error handling by using the ErrorDocument directive. You can specify a message or redirect to a file. The below will display a page named 404.html when a “page not found” error is thrown:
ErrorDocument 404 /404.html
You can also directly use text, like this (note that the message is enclosed in quotes):
ErrorDocument 404 "Oops, that page was not found. We have recorded the error and will look into it.”
You can also add lines for other server error codes. Here are a few more examples:
ErrorDocument 403 "Sorry, you are not permitted to access this."
ErrorDocument 404 /404.php
ErrorDocument 500 "Oops! Our server encountered an error. Try again later."
A list of server error codes can be found here.
This is just the tip of the .htaccess iceberg
The above examples cover the most common uses of .htaccess, but there are even more. Here are some additional .htaccess cheat sheets from around the web:
While .htaccess offers a powerful and fairly simple way to interact with Apache, note that some of these changes can also be accomplished via the cPanel interface. In those instances, the route you choose is a matter of personal preference.
Have fun and remember to back up your original .htaccess file just in case.