我想使用.htaccess将链接到个人资料页面的网址从ID号转换为名称。例如,在Facebook上,如果你要去:
https://facebook.com/profile.php?id=4
您将看到马克·扎克伯格的个人资料页面。但是,您也可以直接访问:
https://facebook.com/zuck
...更加用户友好,更容易记忆。如何使用htaccess将id号转换为用户名?我是否需要将其发送到php脚本来处理并发送回名称?
答案 0 :(得分:4)
您不能专门使用.htaccess
,因为您需要从数据库中获取该ID的用户名,但是您可以使用PHP来执行此操作。
在.htaccess
文件中:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^user/([^/]+)$ /profile.php?user=$1 [L]
然后,您可以在profile.php
:
if(isset($_GET['user'])){
if(is_numeric($_GET['user'])){ //Check if the input is all numeric
//Grab the username from database
//Redirect user to site.com/user/$username
}
}
有关PHP is_numeric()
函数的更多信息:
http://php.net/manual/en/function.is-numeric.php
您可能还想检查用户的用户名是否完全是数字,以避免不断重定向用户。如果你确定用户没有所有的数字用户名,你会没事的。
答案 1 :(得分:0)
由于.htaccess
无法访问存储层,因此您必须使用PHP
脚本将ID
转换为username
1}}然后进行重定向。