在我的web服务器文档根目录中,我创建了包含/index.php
脚本的文件夹/user/
。无论当前(授权)用户是谁,我都需要创建一个页面,向任何人显示我网站上任何用户的信息,我有一个想法,可以使用查询字符串:
site.com/user/?id=3
但我不想这样做。我想要像GitHub一样的URL,像这样:
site.com/user/UserName/
此外,我需要允许URL继续指定请求的"操作",如subscribe
或comments
,以及指定用户名的参数:
site.com/user/Admin/comments/32
site.com/user/Admin/virtual/path/
这应该是对物理路径的简单重写:`/user/index.php `.
我是PHP新手,但我知道mod_rewrite和.htaccess的基础知识,但我仍然不明白如何在我的PHP脚本index.php
中确定URL请求哪个用户(Admin
)和什么操作(comments
)。
请教我如何访问我的网站的URL语法?或者更好的是,如何将/user/Admin/comments
重定向到物理/user/comments.php
。。
- 如何通过保存php脚本的用户名/操作来设置这种动态重写
- 脚本如何访问URL请求的用户名和操作(
comments
、32
) - 我该如何重命名我的问题,因为这个标题似乎不正确
很抱歉长文本,我是干净PHP脚本的新手,谢谢!
如果你真的想自己做,如果你这样做也没关系,这是你需要做的一个例子。我理解不是每个人都需要或想使用框架。
首先,假设您的用户URL是这样的Github示例。
http://www.yoursite.com/user/dmitrij
那么对于.htaccess,你需要一个这样的重写规则。
RewriteEngine On
# check to make sure the request is not for a real file
RewriteCond %{REQUEST_FILENAME} !-f
# check to make sure the request is not for a real directory
RewriteCond %{REQUEST_FILENAME} !-d
#route request to index.php
RewriteRule ^user/([^/]+)/? /user/index.php?id=$1 [L]
然后,如果你想显示评论,你的URL可以看起来像这个
http://www.yoursite.com/user/dmitrij/comments/32
然后你可以使用.htaccess
RewriteEngine On
# check to make sure the request is not for a real file
RewriteCond %{REQUEST_FILENAME} !-f
# check to make sure the request is not for a real directory
RewriteCond %{REQUEST_FILENAME} !-d
#route request to index.php
RewriteRule ^user/([^/]+)/comments/([0-9]+)/? /user/index.php?id=$1&comment_id=$2 [L]
然后,您可以将它们放在两个URL的.htaccess文件中。
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^user/([^/]+)/comments/([0-9]+)/? /user/index.php?id=$1&comment_id=$2 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^user/([^/]+)/? /user/index.php?id=$1 [L]
然后在您的index.php
中,您将检查$_GET
请求这是一个非常简单的例子
<?php
$username = $_GET["id"];
$com_id = $_GET["comment_id"];
print_r($username);
exit;
?>
确保在服务器上启用了mod_rewrite
,并且在vhost或配置文件中设置了AllowOverride All
。
您可以对$_GET
中的值执行任意操作。您必须确保username
在您的数据库中是唯一的。你也可以为不同的URL添加更多的重写,我不会在这里介绍。这应该会给你一个良好的开端。
使用URL重写引擎或使用MVC框架(如symfony
或cakePHP
)开始编程,其中包括
与上面的答案一样,您需要启用mod_rewrite,然后在.htaccess文件中提供映射模式。
我认为您还必须确保您的虚拟主机配置为
`Allow Override ALL`
此页面提供了很好的详细信息-向下滚动到标题为"如何重写URL"的部分。
http://www.smashingmagazine.com/2011/11/02/introduction-to-url-rewriting/