【问题标题】:htaccess - rewrite rule - redirect after url rewritehtaccess - 重写规则 - url 重写后重定向
【发布时间】:2018-04-25 01:30:06
【问题描述】:

这很简单,但似乎无法弄清楚。

我有一个网址 /shows/index.php?id=1,我想在网址中显示为 /shows/1/index.php

所以我将它添加到我的 htaccess 中:

RewriteRule ^shows/([0-9]*)/index.php$ /shows/index.php?id=$1 [L]

这就像一个魅力。我现在可以导航到 /shows/1/index.php 完全没有问题。但是,我仍然可以导航到 /shows/index.php?id=1。我希望该页面自动重定向到新的 url,所以我写了这个:

RewriteRule ^shows/index.php?id=([0-9]*)$ /shows/$1/index.php [R=301,L]

...但它什么也没做。但是,如果我这样做:

RewriteRule ^shows/([0-9]*)/0$ /shows/$1/index.php [R=301,L]

它重定向就好了。所以这让我觉得重写规则的第一部分有问题,也许吧?我对这类东西不太熟悉。

【问题讨论】:

  • index.php 部分是多余的;您真的应该将/shows/?id=42 重写为/shows/42/
  • 会的。谢谢。

标签: .htaccess url-rewriting


【解决方案1】:

由于要重定向和重写同一个请求,需要匹配%{THE_REQUEST}变量,否则重定向时会出现无限循环错误

 RewriteEngine on

# redirect /shows/index.php?id=1 to /shows/1/index.php
RewriteCond %{THE_REQUEST} /shows/index.php\?id=([^\s]+) [NC]
RewriteRule ^shows/index.php$ /shows/%1/index.php? [NC,L,R]
#rewrite /shows/1/index.php to /shows/index.php?id=1
RewriteRule ^shows/([0-9]*)/index.php$ /shows/index.php?id=$1 [L]

在测试之前清除浏览器缓存。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-01
    • 2016-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多