使用nginx通过index.php路由请求


Routing requests through index.php with nginx

我正在将我的服务器从Apache迁移到Nginx,并有这个非常简单的.htaccess规则:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

它背后的想法是将每个请求指向前端控制器(index.php)。我正试图用Nginx做同样的事情。我使用了一个在线转换器来制作这个Nginx位置块:

location / {
    if (!-e $request_filename){
        rewrite ^(.*)$ /index.php break;
    }
}

,但当我把它添加到我的网站的配置Nginx只是吐出PHP文件的源代码作为下载。作为参考,下面是整个配置文件:

http://pastebin.com/tyKtM1iB

我知道PHP的工作原理,如果我删除位置块,使一个文件与<?php phpinfo();正确工作。

这就是我如何将所有内容路由到index.php,包括子目录请求,HTTP参数等。

location / {
    try_files $uri $uri/ /index.php?$args; #if doesn't exist, send it to index.php
}
location ~ '.php$ {
    include fastcgi_params;
    fastcgi_intercept_errors on;
    # By all means use a different server for the fcgi processes if you need to
    fastcgi_pass   127.0.0.1:9000;
 }
例如,这些被发送到index。php:
http://foo.bar/something/
http://foo.bar/something/?something=1

而这些直接进入文件

http://foo.bar/someotherphp.php
http://foo.bar/assets/someimg.jpg

跳过regexp:

location / {
        index index.html index.php;
        if (!-e $request_filename) {
            rewrite ^.* /index.php break;
            fastcgi_pass 127.0.0.1:9001;
        }
}