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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀