Ale*_*uck 1 php .htaccess url-rewriting
我想使用 .htaccess 将链接到个人资料页面的 URL 从 ID 号转换为名称。例如,在 Facebook 上,如果您要访问:
https://facebook.com/profile.php?id=4
Run Code Online (Sandbox Code Playgroud)
它会将您带到马克·扎克伯格的个人资料页面。但是,您也可以简单地访问:
https://facebook.com/zuck
Run Code Online (Sandbox Code Playgroud)
...这对用户更友好并且更容易记住。如何使用 htaccess 将 ID 号转换为用户名?我是否需要将其发送到 php 脚本来处理并发回名称?
您不能专门使用.htaccess
,因为您需要从数据库中获取该 ID 的用户名,但是您可以使用 PHP 来执行此操作。在你的.htaccess
文件中:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^user/([^/]+)$ /profile.php?user=$1 [L]
Run Code Online (Sandbox Code Playgroud)
然后,您可以在以下位置检查类似的内容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
}
}
Run Code Online (Sandbox Code Playgroud)
有关 PHPis_numeric()
函数的更多信息:
http://php.net/manual/en/function.is-numeric.php
您可能还想检查用户的用户名是否完全是数字,以避免不断重定向用户。不过,如果您确保用户没有全数字用户名,那就没问题了。