
Example: Database driven rewrites
Scenario:
In this example, we assume that we run a database driven web application that serves a large number of users and provides a separate home page for each user, for example "http://www.exampleweb.com/username".
As usual, every user has a username and a corresponding id stored in a database. So in order to dynamically create a user's home page, we must do the following conversion:
from: http://www.exampleweb.com/username
to: http://www.exampleweb.com/userpage.csp?user_id=n
To implement this database driven url rewriting, we need to utilize a rewrite configuration that passes the username to an external program which performs a database lookup and returns the corresponding user id. In this example, the scripting language for the external program is JScript.
Configuration:
## Rewrite configuration file
#Turn IIS Mod-Rewrite engine on
RewriteEngine On
#Define a map that executes an external program
RewriteMap users prg:x:\path\usersprg.js
#Create a lock object for RewriteMap program (optional)
RewriteLock usersprg
#The main rule that replaces the username with the user id
RewriteRule ^/([^/]+)/?$ /index.csp?id=${users:$1|0} [L,QSA]
External program script:
// Database lookup function
function Lookup( key )
{
var rs = WScript.CreateObject( "ADODB.Recordset" );
var query = "SELECT ID FROM USERS WHERE USERNAME = '" + key + "'";
var connstring = "DSN=db_name; UID=db_username ; PWD=password";
rs.Open( query, connstring );
if( rs.EOF )return "";
return rs( "USERNAME" );
}
//Main I/O loop -- Keep it this simple!
while ( !WScript.StdIn.AtEndOfStream )
{
var key = WScript.StdIn.ReadLine();
try
{
var value = Lookup( key );
}
catch(e)
{
value = "error";
}
WScript.StdOut.WriteLine( value );
}
|