重定向到重写的 URL
好的,我正在为自定义 PHP 购物车重写一些页面 URL。
我有以下规则:
RewriteRule ^category/([0-9]+)/([a-z-]+)$ /store.php?cat=$1 [L]
RewriteRule ^product/([0-9]+)/([a-z-]+)$ /product.php?id=$1 [L]
这些规则允许我使用像 example.com/product/23/product-slug 这样的 url 结构。
那部分工作正常。我想知道我对另一个方向有什么选择;将旧 url 的请求重定向到新 url。例如,当有人访问 /product.php?id=2 时,我想重定向到 /products/2/slug。
知道如何完成这件事吗?
我尝试了一个简单的重定向,但不起作用:
Redirect 301 ^/store\.php\?cat=16$ http://www.example.com/category/16/category-slug
OK, so I'm rewriting some page URLs for a custom PHP cart.
I've got the following rules:
RewriteRule ^category/([0-9]+)/([a-z-]+)$ /store.php?cat=$1 [L]
RewriteRule ^product/([0-9]+)/([a-z-]+)$ /product.php?id=$1 [L]
These will allow me to use a url structure like example.com/product/23/product-slug.
That part is working alright. I'm wondering what options I have for the other direction; redirecting requests for the OLD url to the NEW url. So for example, when someone goes to /product.php?id=2 I want to redirect to /products/2/slug.
Any idea how to get this done?
I tried a simple redirect, but would not work:
Redirect 301 ^/store\.php\?cat=16$ http://www.example.com/category/16/category-slug
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
重定向仅需要 url 前缀,而不是正则表达式(例如 /store.php 或 /store)
您需要尝试 RedirectMatch:
另外,它是否应该以 / 开头?我不确定(例如,上面的 RewriteRule 条目不以斜线开头)
Redirect only takes a url prefix, not a regex (e.g. /store.php or /store)
You need to try RedirectMatch:
Also, is it supposed to start with a /? I'm not sure (your RewriteRule entries above start with no slash, for example)
我用不同的方式解决了这个问题:修改 store.php 文件。
在 ping 正常的 URL 和重写的 URL 后,我查看了
print_r($_SERVER)
的输出。我发现当正常网址被点击时,$_SERVER['SCRIPT_URL']
包含“/store.php”,而当点击重写网址时,它包含我重写的路径。这意味着我可以做一个简单的测试并适当地重定向:
I solved this a different way: with a modification to the store.php file.
I looked at output from
print_r($_SERVER)
after pinging both the normal and rewritten urls. I found that$_SERVER['SCRIPT_URL']
contains "/store.php" when the normal url is hit and it contains my rewritten path when the rewritten url is hit.This means I can do a simple test and redirect appropriately: