【问题标题】:htaccess redirect URL using partial value of string parameterhtaccess 使用字符串参数的部分值重定向 URL
【发布时间】:2015-06-22 14:45:14
【问题描述】:

我列出了一堆产品

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

我希望这些被重定向到

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

分别。是否有 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

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

\/(\d*?)\-

关于如何在 Apache htaccess 文件中完成此操作有什么想法吗?

【问题讨论】:

  • 您希望在浏览器中将 URL 更改为 https://www.example.com/products.php?p=1234567890 吗?
  • 是的。当向服务器发出https://www.example.com/all/products/foldername/1234567890-ProductDescriptionA-456.html 的请求时,我希望返回https://www.example.com/products.php?p=1234567890。我不关心除了 SOMENUMBERS 中的任何内容:...../foldername/SOMENUMBERS-otherstuff.html
  • 嗯,那么 2 个答案中的任何一个都应该适合您。

标签: regex apache .htaccess


【解决方案1】:

试试这个:

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

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

【讨论】:

  • 我认为 OP 是说前三个 URL 示例是 old 的。因此,那些应该被重定向而不是重写。
  • 这足以让我对其进行调整以使其成功运行。谢谢!
【解决方案2】:

试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-10
    • 2018-01-02
    • 1970-01-01
    • 2021-04-05
    • 1970-01-01
    • 2012-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多