如何在php中创建友好的URL? [英] How to create friendly URL in php?
问题描述
通常,显示某些个人资料页面的做法或非常古老的方法是这样的:
Normally, the practice or very old way of displaying some profile page is like this:
www.domain.com/profile.php?u=12345
其中u=12345
是用户ID.
近年来,我发现一些网站的网址非常好,例如:
In recent years, I found some website with very nice urls like:
www.domain.com/profile/12345
如何在PHP中做到这一点?
How do I do this in PHP?
只是一个疯狂的猜测,这与.htaccess
文件有关吗?您能给我更多有关如何编写.htaccess
文件的提示或示例代码吗?
Just as a wild guess, is it something to do with the .htaccess
file? Can you give me more tips or some sample code on how to write the .htaccess
file?
推荐答案
According to this article, you want a mod_rewrite (placed in an .htaccess
file) rule that looks something like this:
RewriteEngine on
RewriteRule ^/news/([0-9]+)\.html /news.php?news_id=$1
这会映射来自
/news.php?news_id=63
到
/news/63.html
另一种可能性是使用forcetype
进行操作,这会迫使沿特定路径的任何内容都使用php评估内容.因此,在您的.htaccess
文件中,放入以下内容:
Another possibility is doing it with forcetype
, which forces anything down a particular path to use php to eval the content. So, in your .htaccess
file, put the following:
<Files news>
ForceType application/x-httpd-php
</Files>
然后index.php可以基于$_SERVER['PATH_INFO']
变量采取行动:
And then the index.php can take action based on the $_SERVER['PATH_INFO']
variable:
<?php
echo $_SERVER['PATH_INFO'];
// outputs '/63.html'
?>
这篇关于如何在php中创建友好的URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!