EconomicAgent
EconomicAgent

Reputation: 43

htaccess redirect URL using partial value of string parameter

I have a bunch of products listed at

https://www.example.com/all/products/foldername/1234567890-ProductDescriptionA-456.html
https://www.example.com/all/products/foldername/7654321-SomeOtherDesc-B123.html
https://www.example.com/all/products/foldername/93939393-anotherthing-F93939393.html

and I want these to be redirected to

https://www.example.com/products.php?p=1234567890
https://www.example.com/products.php?p=7654321
https://www.example.com/products.php?p=93939393

respectively. Is there an htaccess rule to do string operations on a matched parameter? For example, if I had to convert my URL using Python, it would look like this:

def make_new_url(old_url):
    product_id = old_url.split('/')[-1].split('-')[0]
    new_url = 'https://www.example.com/products.php?p=%s' % product_id
    return new_url

In the old URLs, the product ID is found after the last "/" and just before the first "-". Another regular expression based rule that would work would be:

\/(\d*?)\-

Any thoughts as to how to accomplish this inside an Apache htaccess file?

Upvotes: 4

Views: 220

Answers (2)

samgak
samgak

Reputation: 24417

Try this one:

RedirectMatch ^.*\/(\d+)\-.*$ products.php?p=$1

The rewrite rule matches the number inside a capture group and then substitutes it for $1.

Upvotes: 3

Amit Verma
Amit Verma

Reputation: 41219

Try this :

RedirectMatch ^/all/products/foldername/([0-9]+)-productDiccriptionA-([A-Za-z0-9]+)\.html$ https://example.com/product.php?p=$1

Upvotes: 1

Related Questions