Jun 17, 2012
tom

How to rewrite these URLs?

Question

I am brand new to URL rewriting. I am using an Apache rewriting module on IIS 7.5 (I think). Either way, I am able to do rewrites successfully, but am having trouble on a few key things.

I want this pretty url to rewrite to the this ugly url:

mydomain.com/bike/1234 (pretty) 
mydomain.com/index.cfm?Section=Bike&BikeID=1234 (ugly)

This works great with this rule:

RewriteRule ^bike/([0-9]+)$ /index.cfm?Section=Bike&BikeID$1

Issue #1

I want to be able to add a description and have it go to exactly the same place, so that the useful info is completely ignored by my application.

mydomain.com/bike/1234/a-really-great-bike (pretty and useful)
mydomain.com/index.cfm?Section=Bike&BikeID=1234

Issue #2

I need to be able to add a second or third parameter and value to the url to get extra info for the db, like this:

mydomain.com/bike/1234/5678
mydomain.com/index.cfm?Section=Bike&BikeID=1234&FeatureID=5678

This works using this rule:

RewriteRule ^bike/([0-9]+)/([0-9]+)$ /index.cfm?Section=Bike&BikeID=$1&FeatureID=$2

Again, I need to add some extra info, like in the first example:

mydomain.com/bike/1234/5678/a-really-great-bike (pretty and useful)
mydomain.com/index.cfm?Section=Bike&BikeID=1234&FeatureID=5678

So, how can I combine these rules so that I can have one or two or three parameters and any of the “useful words” are completely ignored?

Asked by Evik James

Answer

I’m assuming that this is Apache and not IIS, based on your examples. You should really learn how regular expressions work, because rewrite rules are basically about figuring out the regular expression.

These rewrite rule should do what you want:

RewriteRule ^bike/([0-9]+)/ /index.cfm?Section=Bike&BikeID$1
RewriteRule ^bike/([0-9]+)/([0-9]+)/ /index.cfm?Section=Bike&BikeID=$1&FeatureID=$2

The $ character is the end-of-line anchor, which means that the expression will only match if the input string ends at that point. By removing the $ we remove this requirement, and therefore ignore any trailing characters.

Answered by mgorven

Related posts:

  1. IIS7 URL Rewrite breaks for URLs containing + characters
  2. Can HAProxy be used to rewrite for pretty URLs?
  3. How can I rewrite urls (ala mod_rewrite) for free in IIS 6?
  4. mod-rewrite: what’s wrong with this simple rewrite to redirect to a subdirectory?
  5. Nginx rewrite urls without redirection

Leave a comment