duanci9305 2013-10-16 15:03
浏览 61
已采纳

在htaccess中使用重定向301或rewriterule重定向并随身携带一个php变量

I think my question is quite simple but I've been banging my head against the wall for the past few hours.

I have my website using rewriterule to ensure messy path names with php variables are now nice and tidy(I've removed [http://www] from my examples because the system thinks I am putting links and won't let me).

So somebody comes to my site at mysite.co.uk/my-product-P1.html the website will know to post mysite.co.uk/product.php?id=1 to the server.

But I also want to tidy it up the other way around. If an old customer or an old link uses the pathname mysite.co.uk/product.php?id=1 then I want it to return mysite.co.uk/my-product-P1.html instead even though the old pathname will actually still work. I don't want customers accessing the same page from different pathnames.

How do I do this and will it create a loop? On another website I have it working using:

RewriteCond %{QUERY_STRING} ^id=1$ [NC]
RewriteRule ^product\.php$ product-P1.html? [R=301,L]

But on that site there are only around 10 products so I'm able to write these lines for each products. On my other site I have hundreds of products so this isn't practical and I need to do it automatically.

Hopefully this makes sense. I have read through other posts and can't find my solution so apologies if this is clearly explained somewhere else.

  • 写回答

2条回答 默认 最新

  • dpbyr64224 2013-10-16 15:08
    关注

    How do I do this and will it create a loop?

    The rules that you have (on the site with 10 products) need to match against the actual request as opposed to the URI:

    RewriteCond %{THE_REQUEST} \ /product\.php\?id=([^\ &]+)
    RewriteRule ^ /product-P%1.html? [R=301,L]
    

    But you're better off doing this in your php script rather than enumerating all the products in the htaccess file:

    On my other site I have hundreds of products so this isn't practical and I need to do it automatically

    You can't do that using only mod_rewrite. You'll need to script that in your product.php script. The product.php script will need to check the $_SERVER'[REQUEST_URI'] php variable, and see if it starts with: /product.php.

    If it does, then you know someone accessed the php script directly, and you'll need to fetch the product name using the id passed in $_GET['id'], then redirect to the product name + "-P$_GET['id'].html".

    The htaccess file and mod_rewrite won't know the mapping between product IDs and product names, so you need to do this in your php script (which does have access to this mapping).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 目标计数模型训练过程中的问题
  • ¥100 Acess连接SQL 数据库后 不能用中文筛选
  • ¥15 用友U9Cloud的webapi
  • ¥20 电脑拓展屏桌面被莫名遮挡
  • ¥20 ensp,用局域网解决
  • ¥15 Python语言实验
  • ¥15 我每周要在投影仪优酷上自动连续播放112场电影,我每一周遥控操作一次投影仪,并使得电影永远不重复播放,请问怎样操作好呢?有那么多电影看吗?
  • ¥20 电脑重启停留在grub界面,引导出错需修复
  • ¥15 matlab透明图叠加
  • ¥50 基于stm32l4系列 使用blunrg-ms的ble gatt 创建 hid 服务失败