Useful .htaccess tips and tricks

Apache web server is the most commenly used web server for hosting sites. You can configure apache using configuration file stored at /etc/apche2/apache2.conf or httpd.conf depending on your setup. Apache also allows configuration at the directory lvel in thr form of .htaccess files. This is quite useful as users won’t have access to httpd.conf file but they can modify the .htaccess files according to their need. The rules you place in the .htaccess file will override the httpd configuration file giving you more control over your site.

You can use htaccess files to many purposes including rewriting urls, adding error documents, and restricting access to certain files or directories and much more. Here are few tips that are helpful if you have a site or blog.

Set TimeZone

You can set the timezone for your server using htaccess.

SetEnv TZ Asia/Calcutta

Set 301 Permanent Redirects

Redirect 301 /old.html

Remove WWW

There is a debate whether to keep www along with the domain name or remove it for SEO purpose. Adding www or skipping it won’t change anything, but it is always better to follow one rule for SEO benefits. If you prefer to skip www from your domain name use the below code.

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^$ [NC]
RewriteRule ^(.*)$$1 [L,R=301]

If you are among those who prefer www along with the domain name use this code.

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^$ [NC]
RewriteRule ^(.*)$$1 [L,R=301]

Rewrite URL

Create pretty permalinks for search engines from dynamic urls

RewriteEngine On
RewriteRule ^([^/]*)/([^/]*)/([^/]*)\.html$ /shop.php?cmd=$1&category=$2&product=$3 [L]

In this case the original URL is http//, with the above rule it will be rewritten to

Hotlink protection

Hotlinking is bad for not only that the other site is stealing your images but in the process waste lot of your bandwidth, to get around this problem you can use these .htaccess rules to prevent that.

This will block images from being hotlinked from your site

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

You can also show an image in place of the hotlinked image

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

Skip the download dialogue

When you try to download files like pdf or doc you will get a request asking you to choose whether to save or open that file for you. To avoid that you can use the below code so the prompt will go directly to save as dialog.

AddType application/octet-stream .pdf .doc .ppt .xls .mov .mp3

Change default index page of a directory

DirectoryIndex myindex.html

Create a custom error page.

If you want to create custom error pages on Linux Apache server, you can use .htaccess to show pretty error documents. After creating the error documents you need to specify them in your .htaccess file. Don’t forget to set the path and filenames to reflect your server path and filename.

ErrorDocument 401 /401.php
ErrorDocument 403 /403.php
ErrorDocument 404 /404.php
ErrorDocument 500 /500.php

If you don’t want to make error documents and just want to show a message, you can do that too.

ErrorDocument 401 Authentication Required
ErrorDocument 403 Forbidden
ErrorDocument 404 Not found
ErrorDocument 500 Internet server error

Block certain IPs Using htaccess

You may want to block some IPs from accessing your site (for example referrer spam), you can block them by putting this code in your .htaccess.

allow from all
deny from

Not only single IPs but you can block a range like this

deny from 72.47 

Compress files

Compressing files will help in reducing the loading time for your site

# compress text, html, and other files
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript

Prevent directory browsing.

You can prevent visitors to a directory which doesn’t have an index file with this rule.

Options All -Indexes

Alternatively you can allow visitors to browse directory with no index file

Options All +Indexes

Restrict file upload limits for PHP

Restrict the uploading file size in PHP, and set the maxiumum execution time for PHP scripts. See how to edit php.ini for increasing memory limit.

php_value upload_max_filesize 10M
php_value post_max_size 10M
php_value max_execution_time 200
php_value max_input_time 200

Set Cache-Control Headers

Set cache control header for different file types, set longer times for static files like images as they won’t change often.

# cache image, pdf files for 5 weeks
<filesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
Header set Cache-Control "max-age=3024000, public"

#cache css, js, xml and text files for 2 days
<FilesMatch ".(js|css|xml|txt)$">
Header set Cache-Control "max-age=172800"

# cache html and htm files for 2 hours
<filesMatch "\.(html|htm)$">
Header set Cache-Control "max-age=7200, must-revalidate"

Protecting files

You can use htaccess to protect specific files from accessing by others using the files directive, protecting .htaccess itself

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