用 PHP 重写 URL
我想将以下网址重写
为www.mysite.com/mypage.php?userid=ca49b6ff-9e90-446e-8a92-38804f3405e7&roleid=037a0e55-d10e-4302-951e-a7864f5e563e
至
www.mysite.com/mypage/userid/ca49b6ff-9e90-446e-8a92-38804f3405e7/roleid/037a0e55-d10e-4302-951e-a7864f5e563e
这里的问题是php文件可以是任何东西。我是否必须为 .htaccess 文件上的每个页面指定规则?
我如何使用 php 中的重写引擎来做到这一点?
I would like to rewrite the following URL
www.mysite.com/mypage.php?userid=ca49b6ff-9e90-446e-8a92-38804f3405e7&roleid=037a0e55-d10e-4302-951e-a7864f5e563e
to
www.mysite.com/mypage/userid/ca49b6ff-9e90-446e-8a92-38804f3405e7/roleid/037a0e55-d10e-4302-951e-a7864f5e563e
The problem here is that the php file can be anything. Do i have to specify rules for each page on the .htaccess file?
how can i do this using the rewrite engine in php?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
要使重写规则发挥作用,您必须将其添加到您的 apache 配置中(在 virtualhost 块中):
RewriteRule
基本上接受两个参数。第一个是描述它应该匹配的内容的正则表达式。这里它正在寻找请求像///roleid/
这样的 url 的用户。第二个参数是它实际上应该在服务器上执行请求的位置(在本例中,是执行请求的 php 文件)。它使用$1
、$2
和$3
引用正则表达式中的组。To get the rewrite rule to work, you have to add this to your apache configs (in the virtualhost block):
RewriteRule
basically accepts two arguments. The first one is a regex describing what it should match. Here it is looking for the user requesting a url like/<mypage>/<pid>/roleid/<rid>
. The second argument is where it should actually go on your server to do the request (in this case, it is your php file that is doing the request). It refers back to the groups in the regex using$1
,$2
, and$3
.不,您不需要为每个 php 文件使用单独的规则,您可以在正则表达式中将文件名变量设置为如下所示:
No you don't need a separate rule for every php file, you can make the filename variable in your regex something like this:
如果要将浏览器中输入的后一个 URL 重写为第一种格式,则需要使用 .htaccess 文件。
但是,如果您想在 PHP 中生成漂亮的 URL(例如用于链接标记),那么您有两个选择。
其次,您可以将第一个(丑陋的)URL 重写为后一个漂亮的URL。然后您需要在 PHP 中使用 preg_replace()。请参阅http://php.net/manual/en/function.preg-replace。 php 了解更多信息。基本上,你会想使用类似的东西
祝你好运!”之类的东西。
If you want to rewrite the latter URL that is entered in the browser TO the first format, you would want to use a .htaccess file.
However, if you want to produce the pretty URLs in PHP (e.g. for use in link tags), then you have two options.
Second, you could rewrite the first (ugly) URL to the pretty latter URL. You would then need to use preg_replace() in PHP. See http://php.net/manual/en/function.preg-replace.php for more info. Basically, you would want to use something like
Good luck!