Sunday, July 22, 2012

Add Security to your PHP projects using .htaccess file

Some days back I published an article about SQL Injection. In this article very small discussion about .htaccess file. After lots of requests I publish this article to add more security to your php application using .htaccess file.

In this tutorial I want to explain about hiding .php extensions and URL rewriting. So improve your Web projects security and quality.


Making .htaccess file

Very simple open any editor like notepad just file save as into .htaccess with in double quotations(".htacess"). You have to upload this file in to hosting root folder, my experience .htaccess file supports only Unix based servers.

Download Sample .htaccess File

Hide .php extension with URL Rewriting

For example if we want to project like Twitter API URLs (Note: Twitter API Developed in Ruby on Rails)


Add this following code in your .htaccess file
RewriteEngine on

RewriteRule ^(.*)\$ $1.php

We can Rewrite index.php into index.html,index.asp,index.sri also


Below code for index.php to index.html
RewriteEngine on

RewriteRule ^(.*)\.html$ $1.php
If you want .asp extension just replace html to asp


Redirecting www URL to non www URL

If you type www.twitter.com in browser it will be redirected to twitter.com.


Add this Following Code:
RewriteEngine On

RewriteCond %{HTTP_HOST} ^www.srinivas.com

RewriteRule (.*) http://srinivas.com/$1 [R=301,L]


Rewriting 'site.com/profile.php?username=foxscan' to 'site.com/foxscan'

My twitter profile http://twitter.com/foxscan its original link passing GET values (http://twitter.com/profile.php?username=foxscan) but this URL is ugly in browser address bar, For user friendly we can change like this.



If you want change like this see the below code
RewriteEngine On

RewriteRule ^([a-zA-Z0-9_-]+)$ profile.php?username=$1

RewriteRule ^([a-zA-Z0-9_-]+)/$ profile.php?username=$1

Download Sample .htaccess File

If any suggestions post a Comment.

2 comments:

Anonymous said...

Very good blog poѕt. Ι absolutеly
appreciate thіs ωebsite. Keep it up!


My pаge ephedra ma huang
My web page > ephedra legal

Anonymous said...

Ӏ uѕеd to bе аblе to find gоoԁ advice from your artiсles.


Also visit my homepаge ... ripped fuel reviews