Tricks with .htaccess

· by

Contents

If your Website is running on an Apache2 Webserver, you can change the behavior of this server with .htaccess-files.

Here are some examples:

Enable htaccess-files

Set AllowOverride to "All":

sudo gedit /etc/apache2/sites-available/default

Restart Apache:

sudo /etc/init.d/apache2 reload

Enable ExpiresOn / mod_rewrite

This is for Ubuntu:

sudo a2enmod
rewrite expires
sudo /etc/init.d/apache2 restart

Prevent or allow directory listing

Add the following line to your .htaccess-file to allow directory listing:

Options +Indexes

Add the following line to your .htaccess-file to prevent directory listing:

Options -Indexes

Prevent Hot Linking

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www.)?your-domain.com/.*$ [NC]
RewriteRule \.(gif|jpe?g|png)$ - [F]

Prevent Direct Access

If you include some files with PHP, you might want that others can't access this file directly. So add the following to your .htaccess-file:

<FilesMatch "\.(inc)\.(php)$">
    Order deny,allow
    Deny from all
</FilesMatch>
<FilesMatch "\.(tpl)$">
    Order deny,allow
    Deny from all
</FilesMatch>