htaccess tips & tricks

Translation of the original in Catalan. Read it in: CatalàCastellano

htaccess is a very powerful configuration file for Apache users. This file can be put in any directory to specify specific behaviors in the Apache configuration. It should also be said that only the users who through the main Apache configuration file inherit permissions to do so will be able to use this type of file.

What can be done from an .htaccess:

  • Specify our own error documents
  • Add specific behaviors according to MIME type
  • Define environment variables
  • Redirect URLs
  • Re-write URLs
  • Restrict access

This document is a translation-adaptation-expansion and everything I felt like changing and adding from the original document: .HTACCESS files useful tips and tricks by Garnet R. Chaney.

UPDATE: The second part of the document is out: more .htaccess tips and tricks

Specifying our own error documents

It is simply about not using the standard errors of the hosting server that hosts our page, that is, we define which page has to be returned in the cases where the HTTP response is not of type 200. The most usual is the 404 (Not Found) error page, if we want to redefine this page we have to put in the .htaccess, for example:

ErrorDocument 404 errors/404.html
Adding specific behaviors according to MIME type

What these server macros do is define specific behaviors according to the file type and return the result after applying the concrete 'parser'. For example:

AddType text/html .shtml
AddHandler server-parsed .shtml

If you want more information about the 'handlers' subject you can consult the manual of Apache handlers use and the documentation of mod_include.

NOTE: Article inspired by: .HTACCESS files useful tips and tricks

Modifying the system environment variables

As you all know the system has a series of environment variables (see env and set) that are visible from the Apache sessions (see phpinfo). Well these can be altered in the following way, for example:

SetEnv SITE_WEBMASTER "Jack Sprat"
SetEnv SITE_WEBMASTER_URI mailto:Jack.Sprat@characterology.com
UnSetEnv REMOTE_ADDR
We add MIME formats

The extensions not recognized by Apache are considered text formats and cannot be downloaded properly, so it is convenient to add the MIME types not recognized by it, for example:

AddType application/x-endnote-connection enz
AddType application/x-endnote-filter enf
AddType application/x-spss-savefile sav
Restricting access to the documents

Apache allows restricting access to the documents according to many types of factors:

  • by host
  • by browser type
  • by the credentials sent via HTTP
  • etc

In the following example access is given only to the IPs of the private network (192.168.*) or to the hosts that end in ymbi.net (domain of my private LAN).

order deny,allow
deny from all
allow from 192.168. ymbi.net
Access protection by authentication

For information about this subject, I recommend: mod_auth manual. It is also worth taking a look at unofficial apache modules like: mod_auth_mysql as its name indicates it allows having the user database not only in text files, but inside a mysql database. There are also similar things for postgresql and for ldap. I would even say I have seen mod_auth_pam interesting, right?

We protect access to only one file

Normally the .htacces refers to a whole directory, therefore if we want to refer only to a specific file we have to specify it with the <Files> directive. In the following example we ask for an authentication to see the quiz.html file, this is checked through the LDAP directory:

<Files quiz.html>
order deny,allow
deny from all
AuthType Basic
AuthName "Characterology Student Authcate"
AuthLDAP on
AuthLDAPServer ldap://directory.characterology.com/
AuthLDAPBase "ou=Student, o=Characterology University, c=au"
require valid-user
satisfy any
</Files>

An example that is always very useful in real life is the following, I even recommend that you use it in the general apache configuration file. What it does is protect so that nobody can read the .htaccess files, since these can contain sensitive information:

<Files .htaccess>
order deny,allow
deny from all
</Files>

There is also a directive called <FilesMatch> and it allows us to use wildcards in the restrictions per file.

Redirecting a client

We can tell the server to redirect the client's connection to a specific URL, there are different types of redirections:

  • permanent - the resource has been moved permanently
  • temp - it has been moved temporarily to another place
  • seeother - the content has been changed
  • gone - the required information has been permanently deleted

Examples:

Redirect permanent /psych/subject/timetable http://www.characterology.com/psych/subject/ttable
Redirect gone /psych/subject/1998
Redirect seeother /psych/subject/1999/ /psych/subject/2000/

More examples:

RewriteEngine on
RewriteBase /psych
RewriteRule test/printenv(.*) cgi-bin/printenv$1

As you can see regular expressions can be used, here you have a small summary:(I haven't translated it so as not to distort it)

  • Patterns ("wildcards") are matched against a string
  • Normal alphanumeric characters are treated as normal
  • Special characters:
  • . (full stop) - match any character
  • * (asterix) - match zero or more of the previous symbol
    • (plus) - match one or more of the previous symbol
  • ? (question) - match zero or one of the previous symbol
  • \? (backslash-something) - match special characters
  • ^ (caret) - match the start of a string
  • $ (dollar) - match the end of a string
  • [set] - match any one of the symbols inside the square braces.
  • (pattern) - grouping, remember what the pattern matched as a special variable

Examples:

  • a+ matches "a", "aaaa", "aaaaaaaaaaaa", but not "bbb"
  • [ab]+ matches, "a", "b", or any length combination of the two
  • \.s?html? matches ".htm", ".shtm", ".html" or ".shtml"
  • (.+)/1999/(.+) matches "subject/1999/psy1011/", and also stores "subject" in 1and"psy1011/"in1 and "psy1011/" in 2.
  • More information: man regex or you even have whole books from O'Reilly house that talk about it Mastering Regular Expressions.

Redirections can be much more complex than what we have seen and we can see here, some examples:

  • We redirect conditionally, for example, when a file doesn't exist:
  • We can also make conditions according to the environment variables:

If you have been left wanting to play more with the subject you can go to the apache documentation concretely where the modules are discussed: mod_rewrite and mod_alias.

As you can imagine this is what I have used to redirect the requests of the blog images, as I was saying in: Are the images and the photo album faster?, here you have the code of the redirection:

RewriteCond %{REMOTE_ADDR} !^192.168.1.0/24
RewriteCond %{REMOTE_ADDR} !^192.168.2.0/24
RewriteCond %{REMOTE_ADDR} !^10.0.30.0/24
RewriteRule ^/article_fitxers(.*) http://dades.joor.net/article_fitxers$1

2 comments

Comments from the old blog, as they were written. Comments are closed.

  1. —

    Un article sobre HTTP rewritting força currat:

    http://www.yourhtmlsource.com/sitemanagement/urlrewriting.html...

  2. —

    petit i complet manual del mòdul mod_rewrite que és el que s'encarrega de fer les redireccions d'URLs reescribint-les.

    mod_rewrite, a beginner's guide (with examples)