CakePHP .htaccess exception for REST API



我正在用CakePHP创建REST API。我的Angular应用程序位于app/webroot/js文件夹中。ui路由器正在工作,但我正在尝试让htaccess为其中包含/rest/的url破例,这样我就可以进行如下的rest调用:/rest/posts.json

这是我的应用程序/webroot/.htaccess:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule (.*)$ index.php/#$1 [L]
    RewriteRule ^rest/.* rest/$1 [L]
</IfModule>

为什么RewriteRule ^rest/.* rest/$1 [L]没有对其上面的index.php catchall破例?

你自己回答了,不是吗?上面的规则是一个catchall,它将捕获所有内容,因此永远不会达到下面的规则(除非您请求的是实际的文件/目录)。

如果您想将rest/* URL指向与index.php#...不同的位置,则必须将其放置在上面。然而,你可能会开始重复自己,因为我想它也应该受到"非文件/目录"条件的约束,所以我可能会对FILENAME条件使用跳过规则,比如

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule . - [S=2]
RewriteRule ^rest/.* index.php [L]
RewriteRule (.*)$ index.php/#$1 [L]

基本上说,如果请求的资源是一个目录或文件,则跳过接下来的两条规则,如果不是,则首先检查当前URL是否以rest/开头,并将其转发到正常的CakePHP进程,而不是使用hash append变体。

最新更新