Author Topic: 5 Useful Apache .htaccess Tricks  (Read 495 times)


  • Administrator
  • Green Belt
  • ***
  • Posts: 225
  • Karma: +0/-0
5 Useful Apache .htaccess Tricks
« on: June 23, 2014, 07:40:28 AM »

A majority of the world’s Internet-connected servers run Apache HTTP Server or one of its derivatives.  This web server software is free and open source, and many system administrators would not trust their servers to run anything else.  One of the great features that Apache offers is its directive system.  Users can add Apache directives directly to the Apache configuration files, virtual host files, or individual .htaccess files for websites.

With .htaccess, users can add directives to their websites without affecting the functionality of every site on the entire web server.  In order to use .htaccess, the AllowOverrides directive must be enabled in the dedicated server’s Apache config file.

1. Index – By default, users will not be allowed to see files contained in a directory with no index page.  Using the following directive, you can allow users to see the contents of a directory.  With other directives, you can also change the visual appearance of directory indexes.

Options +Indexes

2. Password protect directories – With .htaccess and htpasswd, you can set usernames and passwords for directories to prevent unauthorized access.

AuthUserFile /path/to/.htpasswd
AuthType Basic
AuthName “Folder Name”
Require valid-user

3. Error docs – The default Apache error pages are pretty bland.  You can create regular HTML+CSS documents and then use .htaccess to point specific error codes to them.

ErrorDocument 404 /errors/filenotfound.html

4. Rewrite URLs – Many content management systems and scripts use very long URLs containing instruction codes and session IDs.  You can limit those with search-engine-friendly rewritten URLs, thanks to Apache’s mod_rewrite module and an .htaccess file.

RewriteRule ^documents/([0-9]+)(.*)\.html$ documents.php?id=$1

5. Allow/Deny – You can allow or deny access to some or all users with your .htaccess file by either IP address or hostname.  For example, you might want to have a private directory that only you can access from the web.  You could deny all hosts except yours.

allow from deny from all

For more information about .htaccess files, you can consult the Apache tutorials.