If you can control the links that are generated to your /buy/
pages, just insert the product name in the URL (keeping in mind the rules of URLs, like no spaces allowed. Usually, people substitute a -
for spaces). Then modify your rewrite regex to ignore the product name portion of your URL.
RewriteBase /
RewriteRule ^/buy/(.+)/(\d+)/$ ./index.php?p=$2
If you can't control the links, things get more complicated since you'll have to look up the product name using a RewriteMap
and then perform a redirect. I just recently covered this is in a similar question. My answer to that question goes in to greater detail about using RewriteMap
, but I don't think the details of that answer apply to your situation since using a statically-defined list of products probably won't meet your needs.
Basically, you'll need to implement a script that can be called from mod_rewrite's RewriteMap
rule. You'll need something like:
RewriteMap prodname pgm:/path/to/script/namelookup.sh
RewriteRule ^/buy/(\d+)/$ /buy/${prodname:$1}/$1/ [R=permanent]
Where namelookup.sh (or whatever) returns the product's name (on stdout) in a URL-encoded format. You'll definitely want to take a look at mod_rewrite's documentation about using RewriteMap
, specifically the last section of the RewriteMap Directive
on using an external rewriting program.