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

标签 php apache .htaccess nginx front-controller

<分区>

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

RewriteEngine On

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

其背后的想法是将每个请求定向到前端 Controller ( index.php )。我正在尝试对 Nginx 做同样的事情。我使用在线转换器制作了这个 Nginx 位置 block :

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

但是当我将它添加到我的站点的配置中时,Nginx 只是吐出 PHP 文件的源代码作为下载。作为引用,这里是整个配置文件:

http://pastebin.com/tyKtM1iB

我知道 PHP 可以工作,就好像我删除了位置 block 并用 <?php phpinfo(); 创建了一个文件一样它工作正常。

如有任何帮助,我们将不胜感激。

最佳答案

这就是我将所有内容路由到 index.php 的方式,包括子目录请求、HTTP args 等。

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

关于php - 使用 nginx 通过 index.php 路由请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15166445/

相关文章:

javascript - 如果从下拉列表中选择任何选项,则需要输入

php - 如何获得手机、ipad 或平板电脑型号

apache - 在 .htaccess 中阻止 IP 不起作用

PHP password_hash(), password_verify()

php - 在父页面下移动帖子 - Wordpress

java - 如何通过浏览器提供本地文件

使用 Apache 在树莓派 (Debian) 上运行 PHP

java - ValidateJarFile(D :\path\) - jar not loaded. 请参阅 Servlet 规范 3.0,第 10.7.2 节。违规类 : javax/servlet/Servlet. 类

.htaccess - htaccess 将子域重定向到根域

apache - 使用基本身份验证 (htaccess) 限制对特定 URL 的访问