【问题标题】:url rewriting index.phpurl重写index.php
【发布时间】:2010-04-16 12:01:13
【问题描述】:
我有类似的网址
http://mysite.com/index.php?p=resources
http://mysite.com/index.php?p=resources&s=view&id=938
但我想要类似的网址
http://mysite.com/resources
http://mysite.com/resources/view/938
与其制定数百条重写规则,我想知道是否可以只拥有一条?我认为这是可能的,方法是“获取 uri 并将其拆分为多个部分”,然后只需为 index.php 添加重写规则
但是怎么做?有人可以举个例子或链接教程
【问题讨论】:
标签:
php
mod-rewrite
url-rewriting
【解决方案1】:
我碰巧在 .htaccess 中使用了这个:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule .* index.php [L]
无论请求什么,这基本上都会调用 index.php。然后在您的 PHP 代码中,您可以查看 $_SERVER['REQUEST_URI'] 以获取 URL 并相应地对其进行解析。
RewriteCond 行用于排除对文件的直接调用。就我而言,出于性能原因,我不希望 js/css/image 文件请求等内容通过 index.php。
【解决方案2】:
创建一个 .htaccess 文件。不是 somefilename.htaccess,它只是简单地命名为 .htaccess。
注意:您的 index.php 和 .htaccess 文件应该在同一目录中。
现在在你的 .htaccess 文件上试试这个
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^([A-Za-z0-9\-]+)$ index.php?p=resources
RewriteRule ^([A-Za-z0-9\-]+)/([A-Za-z0-9\-]+)/([0-9]+)$ index.php?p=resources&s=view&id=938
</IfModule>
查看更多关于 url 重写here