我想知道是否应该使用.htaccess将get变量更改为数据库中的值(用户名)。
所以如果有
http://www.url.com/user.php?u=1
你怎么把它转换成
http://www.url.com/andrewliu
谢谢!
您需要将user.php
更改为使用用户名而不是用户ID。然后你可以使用类似的东西:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^/?([a-z0-9_-]+)/?$ /user.php?u=$1 [L]
这通过u
查询字符串参数传递用户名,本质上是:/user.php?u=andrewliu
否则,htaccess和mod_rewrite无法知道user_id和username之间的映射是什么。或者,您可以编写数据库脚本并使用RewriteMap为您创建映射:
RewriteMap usermap prg:/path/to/userscript
在你的htaccess中:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^/?([a-z0-9_-]+)/?$ /user.php?u=${usermap:$1} [L]
最后一种选择是,如果你只有5个用户(或少量用户),你可以进行显式重写:
RewriteEngine On
RewriteRule ^/?andrewliu$ /user.php?u=1 [L]
RewriteRule ^/?anotheruser$ /user.php?u=2 [L]
RewriteRule ^/?foousername$ /user.php?u=3 [L]
您需要使用Mod ReWrite。你可以在htaccess文件中使用它,但如果你可以访问httpd.conf文件,它会更快。
理想情况下,您会使用?u=1,然后使用它来查找名称并将名称附加到末尾。否则,你将不得不搜索用户名,并且可能会出现拼写错误等。
RewriteRule ^/([0-9]+)/.*$ /user.php?u=$1 [L]
Stackoverflow就是这样做的,尝试在没有url中的数字的情况下访问此页面,你会得到一个找不到的404页面。正确输入数字,在正斜杠后键入的其他内容将被替换为正确的单词!这更方便!
在php中使用$GET获取'u'的值
然后使用您的逻辑将其转换为名称。
现在只需使用重定向函数转到该URL