正在创建.htaccess文件的虚拟目录


creating virtual directory of .htaccess files

我最近搜索了包括StackOverflow在内的所有论坛,但找不到任何如何使用.htaccess文件的解决方案。我听说虚拟目录是使用此服务创建的。

如果用户名设置为,我希望用户配置文件的虚拟路径显示为这样

www.example.com/username

或者,如果未设置用户名,则用户配置文件将显示此链接

www.example.com/profile.php?id=134531

就像脸书一样。

有人能给我一个确切的代码吗?提前谢谢。

我认为虚拟目录指的是重写。您有一个profile.php页面,通过用户名或id加载用户配置文件。

让我们来讨论您的第一个问题,将/[username]映射到profile.php?username=[username]。此解决方案假定mod_rewrite已安装在Apache服务器上。

RewriteEngine On
RewriteRule ^([a-zA-Z0-9]+)$ profile.php?username=$1 [L]

(将其放在webapp根目录下的.htaccess文件中,或放在Apache conf中的VirtualHost目录中)

这将在内部将任何请求重写为/[username]到profile.php?username=[用户名]。

至于在可用时使用用户名,在不可用时使用id,您必须在生成链接时实现这一点。

<?php
$profile_url = $username ? : 'profile.php?id='.$userid;
?>
<a href="/<?php echo $profile_url; ?>">View profile</a>

这样可以处理链接构建。然后你就有了你的profile.php页面:

$username = $_GET['username'];
$userid = $_GET['id'];
if ($username) {
    /* Load user via username */
} else {
    /* Load user via ID */
}

互联网上有很多关于用Apache重写URL的教程,只需谷歌一下,就可以完成一些测试设置。

这是url重写,查找它,你会发现很多教程