htaccess使用字符串参数的部分值重定向URL

时间:2022-09-17 07:47:50

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:

分别。是否有htaccess规则对匹配的参数执行字符串操作?例如,如果我必须使用Python转换我的URL,它将如下所示:

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:

在旧URL中,产品ID在最后一个“/”之后和第一个“ - ”之前找到。另一个可用的基于正则表达式的规则是:

\/(\d*?)\-

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

有关如何在Apache htaccess文件中完成此操作的任何想法?

2 个解决方案

#1


3  

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.

重写规则匹配捕获组内的数字,然后将其替换为$ 1。

#2


1  

Try this :

尝试这个 :

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

#1


3  

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.

重写规则匹配捕获组内的数字,然后将其替换为$ 1。

#2


1  

Try this :

尝试这个 :

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