【问题标题】:mod_rewrite use variable's numeric position in urlmod_rewrite 在 url 中使用变量的数字位置
【发布时间】:2012-01-25 20:28:31
【问题描述】:

如果标题不太清楚,我深表歉意,因为我是 mod_rewrite 的新手,我不知道如何正确表达问题。

我想将 http://www.url.com/module/subdirectory/another_subdirectory/page 等花哨的 url 重写为 http://www.url.com/ d_1=模块&d_2=子目录&d_3=another_subdirectory&page=page。子目录的数量会有所不同,因此参数 d_* 可以是动态的(尽管尝试将其保持在 d_1 和 d_9 之间)。花哨的 url 也可以有自己的查询字符串,需要重写才能出现在页面参数之后。

我通读了 Apache 的 mod_rewrite 和 regex 文档,并花了一些时间在 Google 和 Stackoverflow 上搜索这个问题的答案,但找不到任何关于这个特定问题的东西。非常感谢知识渊博的人对这个问题的任何帮助。

【问题讨论】:

  • 在应用程序中执行此逻辑要容易得多,例如php。我认为你有充分的理由在 Apache 中尝试这样做
  • 我在自定义 PHP CMS 中使用命名空间运行。每个页面都是其自己文件中的一个类。 url ?d_1=module&d_2=subdirectory&d_3=another_subdirectory&page=page 告诉 CMS 实例化 \Module\Subdirectory\AnotherSubdirectory\Page 类。我想让花哨的网址隐藏正在发生的丑陋。还有另一种我没有看到的方法来解决这个问题吗?

标签: apache .htaccess mod-rewrite


【解决方案1】:

您可以在根目录中的 .htacess 中尝试以下类似操作,但您需要完成最多 9 个案例。

我还假设您的 CMS 应用程序是 index.php。如果不替换为正确的 .php 文件

RewriteEngine on
RewriteBase /

#one subdir
RewriteRule ^module/([^/]+)/([^/]+)$ index.php?d_1=module&d_2=$1&page=$2 [QSA,L,NC]
#two subdir
RewriteRule ^module/([^/]+)/([^/]+)/([^/]+)$ index.php?d_1=module&d_2=$1&d_3=$2&page=$3 [QSA,L,NC]
#three subdir
RewriteRule ^module/([^/]+)/([^/]+)/([^/]+)/([^/]+)$ index.php?d_1=module&d_2=$1&d_3=$2&d_4=$3&page=$4 [QSA,L,NC]

【讨论】:

    【解决方案2】:

    通过将 subdir-parts 设为可选,对 Ulrich 的代码进行了不需要太多重复的更改。最后一部分总是映射到page

    RewriteRule ^(module)/(?:([^/]+)/)?(?:([^/]+)/)?(?:([^/]+)/)?(?:([^/]+)/)?(?:([^/]+)/)?(?:([^/]+)/)?(?:([^/]+)/)?(?:([^/]+)/)?([^/]+)$ index.php?d_1=$1&d_2=$2&d_3=$3&d_4=$4&d_5=$5&d_6=$6&d_7=$7&d_8=$8&page=$9 [QSA,L,NC]
    

    虽然我更愿意为此使用一些 php 代码。

    $dirs = expode('/', $_SERVER['REQUEST_URI']);
    array_shift($dirs);//remove first empty string.
    $page = array_pop($dirs);//get last part of the url.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-21
      相关资源
      最近更新 更多