If I have a URLhttp://www.domain.com/listing.php?company_id=1
is it possible for me to re-write that to http://www.domain.com/company-name
by using that id to pull the name from the database.
Or do I have to change listing.php to make it ?company_name=company-name
If anyone can point me in the right direction that would be great.
Thanks!
A map function allows using no id in the url at all, while still using the id in the rewritten url to do the database lookup.
maps to
Here is how I use map text files, which I generate from a database query. I believe mod_rewrite also does mapping to a database directly, of which I'm unfamiliar (maybe someone can provide that answer). I use Helicon Tech's isapi_rewrite v3, which works like mod_rewrite, so this should work for you.
Sample map file named map_company.txt
The rewrite rules:
RewriteMap assigns the map_company.txt text file to a variable named map_company (named the same just to be consistent).
RewriteRule is doing the work. It captures everything after the slash into
$1
, then rewrites it to your listing.php url. The${map_company:$1}
is looking up the url in the map file, and returning the id.RewriteCond is just doing a double-check to see if the listing is there. The $1 is coming from the RewriteRule url, the NOT_FOUND is a default value if not found, and the condition is if it's not-NOT_FOUND (a little tangled - but it's just checking if it's in the file). If it's in the file, the RewriteRule will be run. If it's not in the file, it skips the RewriteRule, and falls through to more rules (perhaps to a page-not-found or some other default).
You'll need the id in both the urls, but only use the full name in the pretty link for the user. The following would rewrite
http://www.domain.com/42/company_name
tohttp://www.domain.com/listing.php?company_id=42
and just discard the company name.Note that a user could also visit
http://www.domain.com/42/wrong_name
and still land on the right page with the right company name. If this isn't desired you could change the rule to/listing.php?company_id=$1&company_name=$2
and check for equality inlistings.php