URL重写和重定向

时间:2014-05-28 16:05:23

标签: apache url mod-rewrite redirect rewrite

我刚用.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页面重定向到重写规则。

有人对我有想法吗?

3 个答案:

答案 0 :(得分:0)

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

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
}

答案 1 :(得分:0)

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]

答案 2 :(得分:0)

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

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解决方案,并提供了很好的解释,并且它起作用了。

谢谢大家;案件结束:)

相关问题