【问题标题】:How to allow three optional parameters in the URL by .htaccess?如何通过 .htaccess 在 URL 中允许三个可选参数?
【发布时间】:2011-05-31 09:14:24
【问题描述】:

我有http://example.com 和一个PHP 路由类,用于检查某个URL 是否存在。
我想做一条新的路线,就是:

http://example.com/foo/bar/123

但只要我打开它,Apache 就会将我重定向到错误页面。所以我使用的是.htaccess。代码是:

重写引擎开启 RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*) /index.php [L]

只要我使用http://example.com/foo,它就可以工作,但是一旦我添加了一些其他参数,它就会将我重定向到一个错误。

我猜重写代码是错误的。这是错的吗?
如果是的话,你能给我推荐一个好的吗?
如果不是,问题可能出在哪里?

【问题讨论】:

    标签: php apache .htaccess mod-rewrite


    【解决方案1】:

    你可以用php处理URI:

    .htaccess:

    RewriteEngine on
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^ index.php [L]
    

    php:

    if (isset($_SERVER['REQUEST_URI']))
    {
        $params = explode("/", ltrim($_SERVER['REQUEST_URI'], "/"));
        print_r($params);
    }
    

    example.com/just/these/params

    输出:

    Array
    (
        [0] => just
        [1] => these
        [2] => params
    )
    

    【讨论】:

      【解决方案2】:
      RewriteRule ^(.*)$  /$1.php [L]
      

      像这样试试。在您的.htaccess 中,每个不是磁盘文件的请求都被重定向到index.php,我猜index.php 正在进一步重定向。我不认为你可以只用一行代码得到这条路线 /foo/bar/123 或 /foo/bar 。每个页面都需要它自己的重写规则。你能说得更具体一点吗?

      【讨论】:

      • 实际上我想通过 index.php 处理每个 URL,或者至少是 example.com/just/these/params,它会加载我所有的东西并检查该路由是否存在。说:if ($url) 好;否则不好;
      • 您可以使用(.*)^ 捕获任何路径。问题很可能出在index.php
      【解决方案3】:

      我想这会有所帮助。 "/index.php" 将委托给错误的路径。

      RewriteEngine on
      
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule ^ index.php [L]
      

      【讨论】:

        【解决方案4】:

        自 Apache 2.2.16 起:

        FallbackResource /index.php
        

        【讨论】:

        • 请提供某种解释来支持您的回答。
        猜你喜欢
        • 1970-01-01
        • 2016-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多