【问题标题】:URL rewriting and redirectionURL重写和重定向
【发布时间】:2014-05-28 16:05:22
【问题描述】:

我刚刚用 .htaccess 完成了重写,一切正常。

RewriteEngine on
RewriteRule blog/([a-zA-Z0-9\-]+)-([0-9]+)    post.php?url=1&id=$2

我唯一要避免的是重复的内容...我已经搜索了很多关于该主题的内容,遗憾地发现任何内容都符合我的需求。

事实上,重写后的地址“blog/my-new-post-77”也可以通过“post.php?id=77”访问,我不希望它发生。所以我想将每个 post.php 页面重定向到重写的规则。

有人对我有想法吗?

【问题讨论】:

  • 我认为在你的重写规则中应该是url=$1 不是吗?你错过了$ 标记
  • 感谢您的提示 :)

标签: apache url mod-rewrite redirect rewrite


【解决方案1】:

是的,在你的重写规则中添加额外的变量来检查它:

RewriteRule blog/([a-zA-Z0-9\-]+)-([0-9]+)    post.php?check=ok&url=$1&id=$2

在 post.php 文件的顶部,检查 check 变量:

if(isset($_GET['check'])){
  if($_GET['check'] == "ok"){
   //it comes using rewrite rule
   //cut and paste all of your codes in post.php file to here
   //that is which codes are available when user view your page in desired way
   //don't redirect to rewrite rule again here, since visitor came using that rewrite rule to here. doing so will result infinite redirect and will show an error
  }else{
   //this visit is not used rewrite rule to come here
   //here you can redirect visitor to not found page or just show an empty page by putting die();
   //you can't redirect to post pages here, because you don't know what post(id) that visitor need to see
  }
}else{
  //this visit is not used rewrite rule to come here
  //here you can redirect visitor to not found page or just show an empty page by putting die();
  //you can't redirect to post pages here, because you don't know what post(id) that visitor need to see
}

【讨论】:

  • 真是个好主意(没想到我拍了拍额头)!但遗憾的是,它不起作用。仍然可以访问 blog.php?id=77 上的内容。谢谢!
  • 因为您必须将所有代码移动到//it comes using rewrite rule 所在的位置并将die() 或其他内容放入else 块中
  • 哦,我明白了,完全误解了你向我求婚的方式。那么,如果我理解得很好,应该将 header:location 放在 IF 中,而 die() 放在 ELSE 中?很抱歉造成误解。
  • 我编辑了它,将每个地方需要做什么描述为 cmets
  • 嗯,感谢@Janaka 的大力帮助,我会马上尝试的。
【解决方案2】:

post.php?id=77 -> /my-new-post-77 通过浏览器

/my-new-post-77 -> post.php?id=77 通过内部重写

对吗?

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule blog/([a-zA-Z0-9\-]+)\-([0-9]+)$ post.php?url=1&id=$2 [L]

RewriteCond %{THE_REQUEST} \s\/post\.php\?id\=(\d+)\s
RewriteRule . /my-new-post-%1 [R,L]

【讨论】:

  • 我试过了,还是不匹配。忘了准确地说,“my-new-post”,如重写规则中所写,是由 .php?url=1 调用的 dba 行。我修改了它,但仍然可以访问 blog.php?id=77 内容。
  • 您写过关于 post.php 的文章。 my-new-post 必须是脚本 URL 的一部分才能将其捕获到新 URL。
【解决方案3】:

我找到了一个更符合我需求的解决方案。

if($data["url"]!=$_GET["url"]) {
   header("Location:http://www.mywebsite.com/blog/".$data["url"]."-".$data["id"]);          
}

这个解决方案强制 post.php?id=XX 去我们想要的重写位置,同时遇到任何手动 url 重写。

$result 是我的数据库行的 SELECT ALL。

$data = mysqli_fetch_array($result);

我测试了@Janaka 解决方案,您的解释很好,它确实有效。

谢谢大家;结案:)

【讨论】:

    猜你喜欢
    • 2016-06-27
    • 2016-06-18
    • 2015-04-19
    • 2012-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多