【问题标题】:How do I achieve a url like www.example.com/username to redirect to www.example.com/user/profile.php?uid=10? [closed]如何实现像 www.example.com/username 这样的 URL 以重定向到 www.example.com/user/profile.php?uid=10? [关闭]
【发布时间】:2012-04-10 01:06:17
【问题描述】:

在我的网站上,可以通过 URL 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]

【问题讨论】:

标签: php regex apache .htaccess mod-rewrite


【解决方案1】:

.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

【讨论】:

  • 这会将他重定向到www.example.com/user/profile.php?uid=username。但是没有办法通过mod_rewrite从用户名中找到用户的id,所以这当然是正确的做法。 ;-)
  • 感谢您的快速回复,但是我的 .htaccess 文件中已经有这一行 - RewriteRule ^blog/(.+)$ blog.php/$1 [L,NC],它似乎是造成问题。请问我该怎么办?
  • 使用 mod_rewrite 你可以有这个规则:RewriteRule ^(.+)$ user/profile.php?name=$1 [L,QSA] 然后在profile.php 中你可以通过在数据库表中查找名称来将$_GET['name'] 转换为$uid
  • @Chibuzo:你说的 blog.php/$1 是什么意思?
  • @jela:这是不正确的,因为我的第一条规则是避免对任何物理文件、链接或目录进行任何重定向/转发。
【解决方案2】:

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

创建一个 .htaccess 文件并将其上传到 Apache Document Root 并放入以下代码:

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

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

【讨论】:

  • 请详细说明这个答案以改进它。该问题已标记为mod-rewrite,因此用户正在寻找特定答案而不是一般答案。
  • 请看我对第一个答案的评论。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-18
  • 2019-11-11
  • 1970-01-01
相关资源
最近更新 更多