在我的web服务器文档根目录中,我创建了带有/index.php脚本的文件夹/index.php。无论当前(授权)用户如何,我都需要创建一个页面来显示关于的信息--我的站点上的任何用户都是anyone,我有一个使用查询字符串的想法:
site.com/user/?id=3但我不想这样做。我想要类似GitHub的urls,像这样:
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的基础知识,我仍然不知道如何在.htaccess脚本index.php中确定哪个用户(Admin)和什么操作(comments)是由URL请求的。
请教我如何为我的网站达到这个URL语法?或者更好的是,如何将/user/Admin/comments重定向到物理/user/comments.php。
comments,32)对不起,长时间的文字,我是新的清洁PHP脚本,谢谢!
发布于 2015-02-03 20:14:44
如果你真的想自己去做,如果你想做的话,这是你需要做的一个例子。我理解并不是每个人都需要或者想要使用一个框架。
首先,让我们假设您的用户URL是这样的。
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]然后,您可以将所有这些都放在您的.htaccess文件中,供两个URL使用。
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添加更多的重写,我不打算在这里介绍。这应该会给你一个好的开始。
发布于 2015-02-03 19:09:13
使用URL重写引擎或开始使用MVC框架(如symfony或cakePHP )编程,其中包含了功能。
发布于 2015-02-03 19:25:05
与上面的答案一样,您需要启用mod_rewrite,然后在.htaccess文件中提供映射模式。
我认为您还必须确保将虚拟主机配置为
`Allow Override ALL`这个页面提供了很好的细节-向下滚动到题为“如何重写urls”的部分。
http://www.smashingmagazine.com/2011/11/02/introduction-to-url-rewriting/
https://stackoverflow.com/questions/28306712
复制相似问题