Htaccess redirect url using partial value of string parameter

I have a bunch of products listed in

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 them 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 for performing string operations on an agreed 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 identifier is after the last "/" and immediately before the first "-". Another rule based on regex that will work:

\/(\d*?)\-

Any thoughts on how to accomplish this in an Apache htaccess file?

+4
source share
2 answers

Try the following:

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

$1.

+3

:

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

All Articles