Htaccess

From Email Marketing Wiki
Jump to: navigation, search

.htaccess (Hypertext Access) is the default name of Apache's directory-level configuration file. It provides the ability to customize configuration directives defined in the main configuration file. The configuration directives need to be in .htaccess context and the user needs appropriate permissions.

General information

A .htaccess file controls the directory it is in, plus all subdirectories. However, by placing additional .htaccess files in the subdirectories, this can be overruled.

As a configuration file, .htaccess is very powerful. Even the slightest syntax error (like a missing space) can result in severe server malfunction. Thus it is crucial to make backup copies of everything related to your site (including any original .htaccess files) before working with your Hypertext Access file(s). It is also important to check your entire website thoroughly after making any changes to your .htaccess file. In many cases, it is preferable to use cPanel to make these changes for you.

Common usage

There's an almost endless list of things you can do with .htaccess files, but they are not for the faint-hearted. One small error can make your entire site inaccessible. Some of the most useful functions can be done from cPanel, which writes the .htaccess file for you and is generally a safer option than directly editing .htaccess files yourself.

Custom error pages

For more information, see Error pages (cPanel) and List of error pages

The ErrorDocument directive is used to determine what page is shown when a server error occurs.

ErrorDocument 404 my404page.html
ErrorDocument 403 forbidden.html
This code can be used to create any custom page. Certain pages are more complicated to modify - if you create a custom "403 Forbidden" page, then a viewer will not see the custom page. Here is a way to get around this:
ErrorDocument 403 /errors/forbidden.html
In the /errors directory, you may need another .htaccess file, ie:
Order allow,deny
Allow from all
This would allow all users, even those forbidden at /, to access the /errors directory, where the custom 403 page is kept in this example.

Enforce www. for your site (or not)

See also: mod_rewrite

Forcing visitors to include the www. in your address (or forcing them not to) is useful for SEO purposes, to avoid some people using http://yourdomain.com and others using http://www.yourdomain.com.

RewriteEngine On

# Option 1: Rewrite www.domain.com -> domain.com
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^domain\.com [NC]
RewriteRule (.*) http://domain.com/$1 [R=301,L]

# Option 2: Rewrite domain.com -> www.domain.com
#RewriteCond %{HTTP_HOST} .
#RewriteCond %{HTTP_HOST} !^www\.domain\.com [NC]
#RewriteRule (.*) http://www.domain.com/$1 [R=301,L]

### DO NOT USE BOTH OPTIONS!

Password protection

For more information see Password Protect Directories (cPanel)

Make the user enter a name and password before viewing a directory.

AuthUserFile /home/newuser/www/stash/.htpasswd
AuthGroupFile /dev/null
AuthName "Protected Directory"
AuthType Basic
<Limit GET POST>
require user newuser
</Limit>

Now run this command to create a new password for the user 'newuser'.

htpasswd /home/newuser/www/stash/.htpasswd newuser


To unprotect a directory inside an otherwise protected structure:

Satisfy any

Enable SSI

AddType text/html .shtml
AddHandler server-parsed .shtml
Options Indexes FollowSymLinks Includes

Deny users by IP address

Order allow,deny
Deny from 123.45.67.8
Deny from 123.123.7
Allow from all
This would ban anyone with an IP address of 123.45.67.8 and would also ban anyone with an IP address starting in 123.123.7: for example, 123.123.74.42 would not gain access.

Directory listing

If there is no default document (eg index.html) you can have the web server produce a list of files:

Options +Indexes

To stop this behaviour and create an error if there's no default document:

Options -Indexes

To show a fancy list including icon, file size, etc:

Options +Indexes
IndexOptions +FancyIndexing

or to turn of fancy listing:

IndexOptions -FancyIndexing

To stop some files (eg gif and jpg images) being listed:

IndexIgnore *.gif *.jpg

Change the default directory page

DirectoryIndex homepage.html
Here, anyone visiting http://www.yourdomain.com/ would see the homepage.html page, rather than the default index.html.

Redirects

For more information see Redirects (cPanel) or mod_rewrite

Standard temporary redirect

Redirect page1.html page2.html

If someone was to visit http://www.yourdomain.com/page1.html, they would be sent (with a status code of 302) to http://www.yourdomain.com/page2.html

Redirect visitors to a temporary site during site development
During web development, maintenance, or repair, send your visitors to an alternate site while retaining full access for yourself. This is a very useful technique for preventing visitor confusion or dismay during those awkward, web-development moments.

ErrorDocument 403 http://www.alternate-site.com
Order deny,allow
Deny from all
Allow from 99.88.77.66

Send visitors to a subdomain
This rule will ensure that all visitors are viewing pages via the subdomain of your choice:

RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^subdomain\.domain\.com$ [NC]
RewriteRule ^/(.*)$ http://subdomain.domain.tld/$1 [L,R=301]

Prevent hotlinking of images

For more information see HotLink Protection (cPanel)

The following .htaccess rules use mod_rewrite. You only need to include RewriteEngine on once in an .htaccess file, and it may not be required at all if set in the server config file.

To prevent hotlinking from a specific domain:

RewriteEngine on
RewriteCond %{HTTP_REFERER} ^http://([^/]+\.)?baddomain1\.com [NC,OR]
RewriteCond %{HTTP_REFERER} ^http://([^/]+\.)?baddomain2\.com [NC,OR]
RewriteCond %{HTTP_REFERER} ^http://([^/]+\.)?baddomain3\.com [NC]
RewriteRule \.(gif|jpg)$ http://www.example.com/hotlink.gif [R,L]

To prevent hotlinking from anywhere except specific domains:

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?example.com/.*$ [NC]
RewriteRule \.(gif|jpg)$ http://www.example.com/hotlink.gif [R,L]
Unless the image is displayed on example.com, browsers would see the image hotlink.gif.

Note: Hotlink protection using .htaccess relies on the client sending the correct "Referer" value in the http GET request. Programs such as Windows Media Player send a blank referrer, so that attempts to use .htaccess to protect movie files for example are ineffective.

Force file download

You can use the AddType directive to force a file download instead of showing in the user's browser. In your HTML directly link to the file like this: <a href="/movies/mov1.avi">Download Movie1</a>. The user will get a pop-up box asking whether they want to save the file or open it:

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

Prevent files from being cached

This is similar to how google ads employ the header Cache-Control: private, x-gzip-ok="" to prevent caching of ads by proxies and clients.

<FilesMatch "\.(html|htm|js|css)$">
Header set Cache-Control "max-age=0, no-cache, no-store, private"
Header set Pragma "no-cache"
Header set Expires "0"
</FilesMatch>

Remove IE imagetoolbar

<FilesMatch ".(html|htm)$">
Header set imagetoolbar "no"
</FilesMatch>

Show source code instead of executing

If you’d rather have .pl, .py, or .cgi files displayed in the browser as source rather than be executed as scripts. Be very careful with this one!

RemoveHandler cgi-script .pl .py .cgi

Other uses

Some web developers have modified .htaccess to perform custom tasks server-side before serving content to the browser. Developer Shaun Inman shows it is possible to edit .htaccess to allow for server-side constants within CSS.

See also

External links