使用 RegExp 和 Mod Rewrite 重定向 URL

Redirecting URLs using RegExp and Mod Rewrite

在将 Magento 升级到 1.9.3.4 时,它覆盖了 .htaccess 文件,现在我剩下 2000 多个我手动创建的损坏链接。

由于旧的产品 URL 末尾有一个随机数,现在没有了,所以我正在寻找一种重定向它们的方法。

旧 URL 结构:

http://example.com/category-1/subcategory/product-name-1421.html
http://example.com/category-2/subcategory/product-name-5421.html
http://example.com/category-3/subcategory/product-name-5891.html

新 URL 结构:

http://example.com/category-1/subcategory/product-name.html
http://example.com/category-2/subcategory/product-name.html
http://example.com/category-3/subcategory/product-name.html

我知道我可以使用类似 RewriteRule ^category/subcategories/(.+?)(-[0-9]+)?$ category/subcategories/ [L,R=301] 的 RegExp,但我无法让它工作。

我想这可能就是您要找的:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?category/subcategory/(.+?)-\d+\.html$ /category/subcategory/.html [R=301]

为此,您显然需要在您的 http 服务器中激活重写模块。如果你想使用动态配置文件(见下文...),你也需要启用它(见 AllowOverride 指令)。


还有一个一般提示:您应该始终更喜欢将此类规则放在 http 服务器(虚拟)主机配置中,而不是使用动态配置文件(.htaccess 样式文件)。众所周知,这些文件容易出错,难以调试,而且它们确实会降低服务器速度。它们仅在您无法控制主机配置(阅读:非常便宜的托管服务提供商)或您的应用程序依赖于编写自己的重写规则(这是一个明显的安全噩梦)的情况下作为最后的选择提供).