【问题标题】:Url mod_rewrite for static chained pages静态链接页面的 URL mod_rewrite
【发布时间】:2012-11-05 00:59:14
【问题描述】:

如何使用 mod_rewrite 实现这一点?

from:
.com/index.php?menu=home
to:
.com/home

from:
.com/index.php?menu=home&list=hello
to:
.com/home/hello

ALSO(没有文件夹 hierarki)

from:
.com/index.php?menu=home&list=hello
to:
.com/hello

我用这个做第一个:

 RewriteRule ^([^/\.]+)/?$ index.php?menu=$1 [L]

但是如果有多个变量,我该如何连接它们呢?

试过这个:

RewriteRule ^([^/]*)/([^/]*)?$ index.php?home=$1&list=$2

【问题讨论】:

  • multiple variables 是什么意思?如果您在谈论 GET 变量,则需要设置 [L,QSA] 它将所有 GET 参数传递给您的脚本。例如,如果用户转到.com/home/hello?testing=variable,它将把它传递给页面。这是你要求的吗?
  • 更新了我的问题。最后一行。

标签: php url mod-rewrite


【解决方案1】:

您误解了应该如何进行 URL 重写。当您使用MVC 模式时,您的 URL 会告诉框架/引导程序执行哪个控制器和方法。 因此,您的 URL 应该类似于:http://host.com/CONTROLLER/ACTION/what/ever。这就是为什么你不能将.com/index.php?menu=home&list=hello 重写为.com/hello。无法区分 http://host.com/hellocontrolleraction(控制器类的方法)。

下面的代码将重写:

  1. .com/whatever.com/index.php?menu=whatever
  2. .com/whatever/youwant.com/index.php?menu=whatever&list=youwant
  3. .com/whatever/youwant/with/additional/parameters.com/index.php?menu=whatever&list=youwant&additional=$5.

.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)([/])?([^/]*)?([/])?(.*)$ index.php?menu=$1&list=$3&additional=$5 [L,QSA]

【讨论】:

    【解决方案2】:

    一大堆头疼,为什么不创建 1 规则并将路由传递给您的脚本,然后使用 explode() 进行拆分和定义:

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php?route=$1 [L,QSA]
    

    然后在你的 PHP 中

    <?php 
    $route = explode('/',$_GET['route']);
    
    $menu = (!empty($route[0])?:null);
    $list = (!empty($route[1])?:null);
    ?>
    

    顺便说一句,你的第三个例子是不可能的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-17
      • 1970-01-01
      • 1970-01-01
      • 2016-04-03
      • 2021-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多