Forum Moderators: phranque

Message Too Old, No Replies

mod_rewrite with .htaccess

All the tutorials do the reverse of what I want

         

MatthewHSE

1:53 pm on Nov 24, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I have some URL's in the format of:

[mysite.com...]

How can I use mod_rewrite in a .htaccess file to rewrite that URL to something like:

[mysite.com...]

The problem is somewhat complicated by the fact that I'll need two rewrite rules; one for the cat123.cgi portion of the URL and another for the itemid. The reason for this is that going directly to /cat123.cgi with no query string will list all articles in the "Cooking" category. Adding the?itemid=456 query string loads the Pasta article. So wrapping the whole thing up into just one rule may not work for both contexts.

How can I accomplish this, or where is there a tutorial that will explain it? I've read through several, but they all seem to be doing pretty nearly the reverse of what I need.

Thanks in advance,

Matthew

jdMorgan

6:39 pm on Nov 24, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Matthew,

After reading this, I suspect that the reason that "all the tutorials do the reverse" is that mod_rewrite is ill-suited to your needs. If you have many categories and articles, then you will end up with a large number of rewrites, because mod_rewrite in .htaccess context cannot use the RewriteMap directive to build "lookup tables" to convert article numbers to article titles or keywords. A script is better-suited for that purpose.

Another issue is this: mod_rewrite works after an HTTP request is received, but before the content handler is invoked to serve content or activate scripts. Therefore, it cannot be used to change the links which appear on your pages. It can only change the URLs received in client requests, and either redirect to a new URL, or change the "filename" associated with the requested URL.

This is why it is rare to rewrite a dynamic URL with query strings to a static URL.

The "two-part" rewrite is not a problem in itself. mod_rewrite will process an incoming URL through all RewriteRules by default; you must use the [L] flag to override this default behaviour.

In addition to back-references within rulesets, mod_rewrite allows you to define variables and reference them in later rulesets through the [E=var_name:value] flag on RewriteRule, and %{ENV:var_name} tested by RewriteCond. So, you can easily extract a piece of information in one ruleset, save it in a variable, and use it again in subsequent rulesets.

If you do really need to rewrite requested dynamic URLs to static ones, and the above is not helpful, just let us know. It's just far more usual to have your scripts output static URLs, and then let mod_rewrite convert those static URLs back to dynamic ones in order to call your script for subsequent requests.

Jim