php - 如何实现像 www.example.com/username 这样的 url 以重定向到 www.example.com/user/profile.php?uid=10?

标签 php regex apache .htaccess mod-rewrite

<分区>

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

最佳答案

DOCUMENT_ROOT 下的 .htaccess 中使用此代码:

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表。

关于php - 如何实现像 www.example.com/username 这样的 url 以重定向到 www.example.com/user/profile.php?uid=10?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9873641/

相关文章:

php - 指令 'magic_quotes_gpc' 在 PHP 5.3 和更高的 laravel 中被弃用

php - laravel - 三个表的内连接查询

python - 读取电子邮件正文并将每一行放入不同的变量中

java - 阻止单位数字 2,3,4,5 的正则表达式

java - 库更改后主机名与对等方提供的证书主题不匹配

apache - 组合两个 mod_rewrite 规则

ajax - 如何使用 Apache 正确配置反向代理,以用于跨域 AJAX?

php - WSDL 中的数组响应 - SOAP PHP

java - 如何激活ActiveMQ持久化来抵抗重启?

javascript - 在 IE7|8 中用特殊替换模式替换字符串的奇怪行为