Apache + PHP没有" .php"文件扩展名,但包含路径信息

时间:2014-09-23 16:50:52

标签: php apache .htaccess pathinfo

我正在试图弄清楚如何修改.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)。
  3. 我已经通过在.htaccess文件中添加以下内容来了解​​如何执行#1:

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

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

3 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

你可以尝试使用Multiviews,这是为了做到这一点:

Options +Multiviews

答案 2 :(得分:0)

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文件,并运行登录函数。