.htaccess Tips and Tricks

.htaccess is the most useful file when you are developing PHP website and working with PHP and Apache. The directory level configuration of Apache server software is provided via .htaccess (Hypertext access) files.

The htaccess rules falls in four categories as follows :

Redirection
Security
Optimization
Server Settings
In this article we will see different tricks which we can perform with .htaccess file in above categories.

1. Redirection

301 Redirect using .htaccess

If you want to redirect any old file to new one :

Redirect 301 /old/file.html http://yourdomain.com/new/file.html
If you want to redirect the entire site :

Redirect 301 / http://newdomain.com
www to non www redirection

If you dont want to display the www of your site, it is possible with htaccess. Paste the below given code in your .htaccess file.

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www.yourdomain.com [NC]
RewriteRule ^(.*)$ http://yourdomain.com/$1 [L,R=301]
non www to www redirection

Similarly as above, if you want to show www as your sub domain though it is not, just write the given code in your .htaccess file.

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^yourdomain.com [NC]
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [L,R=301]
http to https redirection

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
If you want to redirect only few pages of your site to https, below is the code :

RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} page-1 [OR]
RewriteCond %{REQUEST_URI} page-2 [OR]
RewriteCond %{REQUEST_URI} page-3
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
https to http redirection

RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}
Custom Error Pages

Showing custom page when 404 error occurs.

ErrorDocument 404 /404.php
Same for other error pages too.

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

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

2. Security

Protect .htaccess File

In order to protect your .htaccess file, .htaccess is used. Take a look over the below given code :

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

The following block of code will prevent the users to access your file, also it can be done for multiple file types.

# prevent viewing of a specific file
<Files secretfile.jpg>
order allow,deny
deny from all
</Files>

# multiple file types
<FilesMatch “.(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$”>
order allow,deny
deny from all
</FilesMatch>
Deny visitors by IP address

Order allow,deny
deny from 255.0.0.0
deny from 255.0.0.1
allow from all
As per this code, the users from IP 255.0.0.0 and 255.0.0.1 would be blocked. But if you want to block all the other visitors except you, the below code will be helpful for you.

Order allow,deny
allow from 255.0.0.0
deny from all
Deny visitors based on domains :

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_REFERER} example.com [NC,OR]
RewriteCond %{HTTP_REFERER} demo.com [NC,OR]
RewriteRule .* – [F]
</ifModule>
Now the visitors from the domain example.com and demo.com will not be able to visit your site.

Deny visitors based on User-Agent Header

<IfModule mod_rewrite.c>
SetEnvIfNoCase ^User-Agent$ .*(craftbot|download|extract|ninja|clshttp|webspider|leacher|collector|grabber|webpictures) HTTP_SAFE_BADBOT
SetEnvIfNoCase ^User-Agent$ .*(libwww-perl|aesop_com_spiderman) HTTP_SAFE_BADBOT
Deny from env=HTTP_SAFE_BADBOT
</ifModule>
This could block certain spider from crawling your site and thus save your bandwidth.

Deny request from invalid characters

For better security, you can deny the requests coming from invalid characters by writing the below code.

Apache

RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} !^[A-Z]{3,9} [a-zA-Z0-9.+_/-?=&]+ HTTP/ [NC]
RewriteRule .* – [F,NS,L]
Prevent directory listing

IndexIgnore *
But if you only want to ignore certain files, you can use below code block.

IndexIgnore *.gif *.jpg
Hot links prevention

Hot link is, when some one else displays your site’s javascript files, or css files, or images directly by linking to your site’s url. Such hot links consume your bandwidth, but htaccess provides a way to prevent hot links.

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www.)?mydomain.com/.*$ [NC]
RewriteRule .(gif|jpg|js|css)$ – [F]
Note: Just add your site url instead of mydomain.com.

Rename htaccess file

For security purpose you can rename your .htaccess file to prohibit its access.

AccessFileName htacc.ess

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

3. Optimization

Compress Output

You can compress your css/js and other files using GZIP compression. Gzip is very much important for saving the bandwidth and visitors’ time. Just paste the following code in your .htaccess file and it will compress your css, js, html and other mentioned files.

#Gzip – compress text, html, javascript, css, xml
<ifmodule mod_deflate.c>
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
</ifmodule>
#End Gzip

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
4. Server Settings

Set Directory Index :

Usually your directory index is index.html or index.php, but it is good to change the default page using .htaccess.

DirectoryIndex index.php index.html custom_page.php
Scripts to display as code :

If you need to display the script as source code, it can be done by adding two lines of code in the htaccess file.

RemoveHandler cgi-script .pl .cgi .php .py
AddType text/plain .pl .cgi .php .py
Force download file :

If you want some files to be download before it is played in the browser, attach the following piece of code :

AddType application/octet-stream .zip .mp3 .mp4
Here the file types given are downloaded before being played. You can also specify others as per need.

Limit the size of file upload :

Apache

php_value upload_max_filesize 20M
php_value post_max_size 20M
php_value max_execution_time 200
php_value max_input_time 200


Discover more from mycodetips

Subscribe to get the latest posts sent to your email.

Discover more from mycodetips

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top