Wednesday, August 13, 2003

Search Engine Safe URL's in Apache 2

I've figured out an easy way to employ search engine safe url's on unix and apache2. It has always been possible to implement them with mod_rewrite, but its difficult to do globally for url's like this: www.site.com/page.cfm/id/4

Here's the script

<cfif NOT Find(".", cgi.path_translated)>
	<cfset webroot = GetPageContext().GetServletContext().getRealPath("/")>
	<cfset query_string = RemoveChars(cgi.path_translated, 1, Len(webroot))>
	<cfset urlArray = ListToArray(query_string, "/")>
	<cfset urlArrayLen = ArrayLen(URLArray) - 1>
	<cfloop index="i" from="1" to="#urlArrayLen#" step="2">
		<cfset url[urlArray[i]] = urlArray[i + 1]>
	</cfloop>
</cfif>

So you just need to include that in your Application.cfm, or in pages that need to use search engine safe url variables. NOTE that I'm pretty sure this will only work on Apache 2, and may need some tweaking to get it to work on windows with apache (probably just have to make sure the paths use /). This was tested on Apache 2.0.46 on Redhat9, it also works in a multi-homed environment (virtual hosts). One thing it will ignore are query string's with dot's in them.

I will write up an article explaining how this works when I have more time, but for now enjoy the code.