.htaccess For All — SitePoint (2024)

Htaccess (HyperText Access) is a simple configuration file that allows designers, developers and programmers alike to alter the configuration of the Apache Web Server in order to provide additional functionality. Such functionality can include redirecting users, URL re-writes and providing password-protected directories; but it can do so much more.So let’s begin …

Creating and Uploading an .htaccess File

Creating an .htaccess file is very easy.Simply open Notepad or a similar text-based program, switch off word-wrap, add the code and save the file in the usual way.For example, you could call it:

htaccess.txt

Upload the file to the relevant directory on your web server and then rename it like so:

.htaccess

Remember, the .htaccess file should be using 644 permissions and uploaded in ASCII mode. If your .htaccess file does not work, then you should contact your system administrator or web hosting company and ensure they have enabled ‘.htaccess’ within your account, as some web hosting companies do not allow its use without prior permission. Unfortunately, .htaccess will not work on Windows-based servers.

Using .htaccess

It is important to remember that an .htaccess file will affect the directory it is placed in and all resulting sub-directories. Therefore, if you add your ‘.htaccess’ file to the ‘web site root’ then it will affect all subsequent folders like so:

http://www.yourdomain.com/| -- directory1| -- directory2| -- directory3| | -- directory3/childdirectory1| | -- directory3/childdirectory2| -- .htaccess| -- index.html

However, if you place the ‘.htaccess’ file in http://www.yourdomain.com/directory1 then the features of the ‘.htaccess’ will be restricted to that folder and all child folders only. For example:

http://www.yourdomain.com/| -- directory1| | -- directory1/childdirectory1| | -- directory1/childdirectory2| | -- directory1/childdirectory3| | | -- directory1/childdirectory3/newdirectory1| | | -- directory1/childdirectory3/newdirectory2| | -- .htaccess| | -- index.html

After editing your .htaccess file on multiple occassions it may look a little complicated so I would recommend implementing comments. To do this, simply place the hash symbol at the beginning of every line like so:

# comment here# another comment here

Useful Snippets

And to get you started, it’s snippet time …(although one or two of them are strictly directives for Apache)

Directory Index

You can change a default index file of directory with:

DirectoryIndex welcome.html welcome.php

Custom Error Pages

You can redirect your users to an error page with:

ErrorDocument 404 error.html

And you can extend this like so:

ErrorDocument 400 /400.htmlErrorDocument 401 /401.htmlErrorDocument 403 /403.htmlErrorDocument 404 /404.htmlErrorDocument 500 /500.htmlErrorDocument 502 /502.htmlErrorDocument 504 /504.html

But remember to create your error pages!

Remove the Need for www in Your URL

Keep your site consistent by removing the need for ‘www’ by using:

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

Set the Time Zone for Your Server

SetEnv TZ Europe/London

Control Access to Files

Most people will remember that .htaccess is most often used to restrict or deny access to individual files and folders and you can do this like so:

deny from all

However, if you would like to be more specific and ban a specific IP address then you could use:

order allow,denydeny from XXX.XXX.XXX.XXXallow from all

or alternatively for several IP addresses, you could use:

allow from alldeny from 145.186.14.122deny from 124.15

301 Permanent Redirects

Worried about those old links? Then try:

Redirect 301 /olddirectory/file.html http://www.domainname.com/newdirectory/file.html

Set the Email Address for the Server Administrator

By using the following code you can specify the default email address for the server administrator:

ServerSignature EMailSetEnv SERVER_ADMIN webmaster@domain.com

Detecting Tablets and Redirecting

If you would like to redirect tablet-based users to a particular web page or directory, try:

RewriteCond %{HTTP_USER_AGENT} ^.*iPad.*$RewriteRule ^(.*)$ http://yourdomain.com/folderfortablets [R=301]RewriteCond %{HTTP_USER_AGENT} ^.*Android.*$RewriteRule ^(.*)$ http://yourdomain.com/folderfortablets [R=301]

Link Protection

Concerned about hotlinking or simply want to reduce your bandwidth usage? Try experimenting with:

Options +FollowSymlinksRewriteEngine OnRewriteCond %{HTTP_REFERER} !^$RewriteCond %{HTTP_REFERER} !^http://(www.)?domainname.com/ [nc]RewriteRule .*.(gif|jpg|png)$ http://domainname.com/img/hotlink_f_o.png [nc]

Force “File Save As”

If you would like force users to download files rather than view them in the browser you could use:

AddType application/octet-stream .csvAddType application/octet-stream .xlsAddType application/octet-stream .docAddType application/octet-stream .aviAddType application/octet-stream .mpgAddType application/octet-stream .movAddType application/octet-stream .pdf

or you simplify this as:

AddType application/octet-stream .avi .mpg .mov .pdf .xls .mp4

Rewrite URLs

If you would like to make your URLs a little easier to read (ie changing content.php?id=92 to content-92.html) you could implement the following ‘rewrite’ rules:

RewriteEngine onRewriteRule ^content-([0-9]+).html$ content.php?id=$1

Redirect Browser to https

This is always useful for those who have just installed an SSL certificate:

RewriteEngine OnRewriteCond %{HTTPS} !onRewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Activate SSI

If you want to activate SSI for HTML and or SHTML file types, try:

AddType text/html .htmlAddType text/html .shtmlAddHandler server-parsed .htmlAddHandler server-parsed .shtmlAddHandler server-parsed .htm

Disable or Enable Directory browsing

# disable directory browsingOptions All -Indexes# enable directory browsingOptions All +Indexes

Change the Charset and Language headers

For those who want to change the current character set and language for a specific directory use:

AddDefaultCharset UTF-8DefaultLanguage en-GB

Block Unwanted Referrals

If you want to block unwanted visitors from a particular website or range of websites you could use:

<IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{HTTP_REFERER} website1.com [NC,OR] RewriteCond %{HTTP_REFERER} website2.com [NC,OR] RewriteRule .* - [F]</ifModule>

Block Unwanted User Agents

With the following method, you could save your bandwidth by blocking certain bots or spiders from trawling your website:

<IfModule mod_rewrite.c>SetEnvIfNoCase ^User-Agent$ .*(bot1|bot2|bot3|bot4|bot5|bot6|) HTTP_SAFE_BADBOTSetEnvIfNoCase ^User-Agent$ .*(bot1|bot2|bot3|bot4|bot5|bot6|) HTTP_SAFE_BADBOTDeny from env=HTTP_SAFE_BADBOT</ifModule>

Block Access to a Comprehensive Range of Files

If you want to protect particular files, or even block access to the .htaccess file, try customising the following code:

<Files privatefile.jpg> order allow,deny deny from all</Files><FilesMatch ".(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$"> Order Allow,Deny Deny from all</FilesMatch>

And Lastly …

For reasons of security alone, I think the chance to rename the .htaccess file is very useful:

AccessFileName ht.access

In writing this article I have tried to highlight the range of functions htaccess can be used for. Of course, I haven’tcovered everything but as you can see, .htaccess might be an old tool but it still has an important role to play in enhancing your website.

FAQs on Mastering .htaccess for Website Optimization and Security

What is the purpose of an .htaccess file in website development?

The .htaccess file is a configuration file used by Apache-based web servers that allows you to control and modify your website’s behavior without needing to alter the server configuration files. It provides a way to make configuration changes on a per-directory basis. Some of the things you can do with an .htaccess file include redirecting URLs, preventing hotlinking, password protecting directories, enabling or disabling CGI scripts, and more. It’s a powerful tool that can greatly enhance the functionality and security of your website.

How do I create an .htaccess file?

Creating an .htaccess file is straightforward. You simply create a new file and name it “.htaccess”. Note that the file name starts with a dot and there is no file extension. You can create this file using any text editor, but make sure to save it in ASCII format. Once created, you can upload the file to your server using an FTP client. Remember, the .htaccess file should be uploaded to the directory that you want to affect.

How can I use .htaccess for URL redirection?

URL redirection is a common use of .htaccess files. This is often used when a page has been moved and you want to redirect visitors to the new location. Here’s a simple example of how to do this:

Redirect 301 /oldpage.html /newpage.html

In this example, any visitor trying to access “oldpage.html” will be automatically redirected to “newpage.html”.

Can I use .htaccess to improve my website’s security?

Yes, .htaccess files can be used to enhance your website’s security. For example, you can use .htaccess to restrict access to certain directories by IP address, or to password-protect directories. You can also use it to disable directory listings, which can prevent unauthorized users from seeing a list of files in your directories.

How can I use .htaccess to prevent hotlinking?

Hotlinking is when another website links directly to files (especially images) on your website, using your server’s bandwidth to display the content on their site. You can prevent this by adding the following code to your .htaccess file:

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

Replace “yourdomain.com” with your actual domain name. This code will prevent any site other than yours from displaying your images.

How can I password protect a directory using .htaccess?

You can use .htaccess to password protect a directory on your website. This involves creating a .htpasswd file that contains the usernames and passwords of authorized users, and then adding code to your .htaccess file to specify the directory to be protected and the location of the .htpasswd file. Here’s an example:

AuthType Basic
AuthName "Restricted Content"
AuthUserFile /path/to/.htpasswd
Require valid-user

In this example, replace “/path/to/.htpasswd” with the actual path to your .htpasswd file.

Can I use .htaccess to enable or disable CGI scripts?

Yes, you can use .htaccess to control the execution of CGI scripts. For example, you can add the following code to your .htaccess file to enable CGI scripts in a specific directory:

Options +ExecCGI
AddHandler cgi-script .cgi .pl

This code enables the execution of CGI scripts with the extensions .cgi and .pl.

How can I use .htaccess to customize error pages?

You can use .htaccess to display custom error pages instead of the default server error pages. For example, to display a custom 404 error page, you would add the following code to your .htaccess file:

ErrorDocument 404 /custom_404.html

In this example, replace “/custom_404.html” with the path to your custom 404 error page.

Can I use .htaccess to control caching?

Yes, you can use .htaccess to control how your website’s content is cached by browsers. This can help to improve your website’s load times. Here’s an example of how to do this:

<IfModule mod_expires.c>
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 text/html "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 1 month"
</IfModule>

This code sets different caching times for different types of files.

How can I use .htaccess to improve my website’s SEO?

.htaccess can be used to improve your website’s SEO in several ways. For example, you can use it to implement 301 redirects for moved pages, which can help to preserve your search engine rankings. You can also use it to rewrite URLs to make them more SEO-friendly. Here’s an example of how to do this:

RewriteEngine On
RewriteRule ^product/([0-9]+)/?$ product.php?id=$1 [NC,L]

In this example, a URL like “product.php?id=123” would be rewritten as “product/123”. This type of URL is generally considered to be more SEO-friendly.

.htaccess For All — SitePoint (2024)
Top Articles
Latest Posts
Article information

Author: Duane Harber

Last Updated:

Views: 5567

Rating: 4 / 5 (51 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Duane Harber

Birthday: 1999-10-17

Address: Apt. 404 9899 Magnolia Roads, Port Royceville, ID 78186

Phone: +186911129794335

Job: Human Hospitality Planner

Hobby: Listening to music, Orienteering, Knapping, Dance, Mountain biking, Fishing, Pottery

Introduction: My name is Duane Harber, I am a modern, clever, handsome, fair, agreeable, inexpensive, beautiful person who loves writing and wants to share my knowledge and understanding with you.