Saturday 9 February 2013

.htaccess | mod_rewrite - Request routing in Apache

As a web app developer It's great to be able to disconnect your URL convention from your file structure.

But Brian, why would I want to do that? I'm glad you asked ;) 

let say you have a blog site and you want people to be able to find your post by entering something like "". Without using a htaccess + mod_rewrite module you would need to use URL parameters. The above would look like "" or even worse; create directories and subdirectories to represent your URL space. This would be stupid as your posts are stored in your database... right!?

?? htaccess ?? mod_rewrite ??

Ok a little bit more background: Your Apache web server uses dot htaccess files to allow for more controls on specific file and directory with in your site. The mod_rewrite is a rewrite engine that allows you to state rules on how urls should be managed as they come in.

So what we are going to do is
  1. Route incoming requests to one file that will decide what should be displayed.
  2. Allow access to resource files like Images, Css, Js and the hackers.txt.


#This is a comment
#enable the mod_rewrite module
RewriteEngine on

#RewriteRule Pattern Substitution [Options]

#allow access to all files in the img directory
RewriteCond %{REQUEST_URI}  /img/.$
#the [L] flag means that if the rule matches, no further rules will be processed
RewriteRule .* - [L]

#allow access to all files in the css  directory
RewriteCond %{REQUEST_URI}  /css/.$
RewriteRule .* - [L]

#allow access to only  js and coffee  files in the js  directory
RewriteCond %{REQUEST_URI}  /js/.+(js|coffee)$
RewriteRule .* - [L]

#allow access to this particular hacker.txt
RewriteCond $1 !^(hacker\.txt)

#all other request are to be send to index.php
RewriteRule ^(.*)$ /index.php/$1 [L]
Let me know if this was of any help.

No comments:

Post a Comment