如何获取www.example.com/username等网址以重定向到www.example.com/user/profile.php?uid=10?

时间:2012-03-26 14:06:23

标签: php regex apache .htaccess mod-rewrite

在我的网站上,网址www.example.com/user/profile.php?uid=3可以访问用户个人资料 我想通过简单地请求www.example.com/username

让用户更轻松地访问他们的个人资料

每个用户都有一个无法更改的用户名。我怎样才能做到这一点?

Here is my current .htaccess file

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME} !-d
# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME} !-f
# If the request is not for a valid link
RewriteCond %{REQUEST_FILENAME} !-l
# finally this is your rewrite rule
RewriteRule ^blog/(.+)$ blog.php/$1 [L,NC]
RewriteRule ^(.+)$ user_page/profile.php?uid=$1 [L,QSA]

2 个答案:

答案 0 :(得分:7)

.htaccess下的DOCUMENT_ROOT

中使用此代码
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

# If the request is for a valid directory
RewriteCond %{REQUEST_FILENAME} -d
# If the request is for a valid file
RewriteCond %{REQUEST_FILENAME} -f
# If the request is for a valid link
RewriteCond %{REQUEST_FILENAME} -l
# do not do anything
RewriteRule ^ - [L]

# forward /blog/foo to blog.php/foo
RewriteRule ^blog/(.+)$ blog.php/$1 [L,NC]

# forward /john to user_page/profile.php?name=john
RewriteRule ^((?!blog/).+)$ user_page/profile.php?name=$1 [L,QSA,NC]

现在在profile.php内,您可以通过在数据库表中查找用户名来将$_GET['name']翻译为$uid

答案 1 :(得分:2)

如果你有 Apache ,你应该 mod_rewrite 模块。

创建 .htaccess 文件并将其上传到Apache 文档根目录并输入以下代码:

RewriteEngine on
RewriteRule ^(.+)$ user/profile.php?username=$1

这会使用用户名参数将用户名传递给 user / profile.php ,您可以在profile.php中获取用户名,然后进行SQL查询以获取用户个人资料。