【问题标题】:creating virtual directory of .htaccess files创建 .htaccess 文件的虚拟目录
【发布时间】:2012-03-11 01:43:02
【问题描述】:

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

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

www.example.com/用户名

或者如果没有设置用户名,那么用户配置文件将与这个链接一起显示

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

就像脸书一样。

谁能给我一个确切的代码?提前致谢。

【问题讨论】:

  • 您正在寻找“Mod rewrite”或“RewriteRule”,这将为您带来更好的搜索结果。有数百万页专门用于此。
  • 他们都没有帮助,因为我对 .htaccess 一无所知,一个字也不懂
  • 创建你所称的“虚拟目录”是使用 Mod Rewrite 和 Rewrite Rules 完成的。我敢肯定,如果您花 1 分钟以上的时间查找它,您会找到更多信息。
  • 好的,但是如何创建 .htaccess 文件?只需将其命名为 .htaccess ?
  • 是的,将其粘贴到您网站的根文件夹中。

标签: php .htaccess


【解决方案1】:

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

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

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

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

这将在内部将任何对 /[username] 的请求重写为 profile.php?username=[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 重写的教程,只需 google 并通过一些测试设置即可。

【讨论】:

  • 好的,我明白了,但是这段代码重定向到 profile.php,我想要它。
  • 我希望如果用户进入页面 profile.php?id=153511 而不是重定向到 example.com/username 这个页面
  • 所以,这样做,检查用户名是否设置,如果没有,重定向到用户名页面
【解决方案2】:

就是url改写,找找会发现很多教程

【讨论】:

  • 他们都没有帮助,因为我对 .htaccess 一无所知,一个字也不懂
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-30
  • 1970-01-01
  • 2010-09-20
  • 1970-01-01
  • 2011-12-26
  • 2012-05-07
相关资源
最近更新 更多