【问题标题】:Apache + PHP without ".php" File Extension but Including Path Info没有“.php”文件扩展名但包含路径信息的 Apache + PHP
【发布时间】:2014-11-17 23:31:41
【问题描述】:

我正在尝试弄清楚如何修改 .htaccess 文件,以便我可以做两件事:

  1. 不必在我的 PHP 文件中包含 .php 扩展名(例如,对 my.domain.com/page 的请求映射到 my.domain.com/page.php)。
  2. 执行 #1,同时还包括其他路径信息(例如,对 my.domain.com/page/path/stuff/here 的请求映射到 my.domain.com/page.php/path/stuff/here)。

通过将以下内容添加到 .htaccess 文件中,我发现了如何执行 #1:

# Allow PHP files without ".php" extension.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/.]+)/?$ /$1.php [L,QSA]

但是,现在我想修改 RewriteRule,使其适用于 #2。

【问题讨论】:

    标签: php apache .htaccess pathinfo


    【解决方案1】:

    好的,在搜索 MultiViews 之后,我发现了几篇警告他们的文章(嗯,每个人都有自己的),但这也让我得到了一个使用 2 条规则而不是 1 条规则的答案:

    RewriteRule ^([^\.]+)$ /$1.php [L]
    RewriteRule ^([^\./]+)/(.*) /$1.php/$2 [L]
    

    第一条规则捕获上面的案例#1,第二条规则捕获上面的案例#2。瞧!

    【讨论】:

      【解决方案2】:

      您可以尝试使用Multiviews,它就是这样做的:

      Options +Multiviews
      

      【讨论】:

        【解决方案3】:
        RewriteEngine On # Turn on the rewriting engine
        RewriteRule ^([^\.]+)$ $1.php [NC,L] #Remove the .php
        

        但不确定你想要什么路径的东西。

        根据您的评论进行编辑,我在 php/angular 中使用过类似的东西。这可能不是“正确”或最好的方法,但它对我有用。

        Htaccess

        RewriteEngine       on
        # Allow the API to function as a Front Controller
        RewriteRule         ^api/(.*)$ api/index.php?rt=$1 [L,QSA,NC]
        # Allow Angular to have Pretty URL's
        RewriteCond         %{REQUEST_FILENAME} !-f
        RewriteCond         %{REQUEST_FILENAME} !-d
        

        api/index.php

        // Pull the routing path
        $router = explode('/', $_GET['rt']);
        
        $version = $router[0];
        $controller = $router[1];
        $action = $router[2];
        
        // Check for the file
        if(file_exists($version . '/controllers/' . $controller .'.class.php')) {
            include $version . '/controllers/' . $controller .'.class.php';
        } else {
            return false;
        }
        
        // Initialize and execute
        $method = new $controller($action);
        print $method->$action();
        

        这让我可以在 url 中执行类似的操作:api/v1/users/login,然后会在 V1 文件夹中找到 users.class.php 文件,并运行函数 login。

        【讨论】:

        • 除了NC,L外,和OP一样。请始终在您的答案中添加解释(NC,L 是什么意思?)。
        • 有点,但不是真的。正则表达式是不同的。另外:L = LastNC = nocase.
        • 不幸的是,它没有这样做。但要回答 jassok 的问题,这是一种使 HTTP 请求更具体的方法。您可以从 pathinfo 中获取数据,以确定要执行哪个函数,从而确定查询字符串或表单数据中的哪些数据,以及要返回的内容。这样你就可以为多个相关请求编写一个控制器。
        • 我对帖子进行了一些编辑,听起来你在考虑前端控制器?我可能完全错了,但我编辑了我的帖子以显示我过去在使用自定义 php 控制器弄乱 AngularJS 时使用的类似内容。
        猜你喜欢
        • 2011-03-24
        • 1970-01-01
        • 2020-04-05
        • 2017-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-24
        • 1970-01-01
        相关资源
        最近更新 更多