【问题标题】:Routing requests through index.php with nginx [closed]使用 nginx 通过 index.php 路由请求 [关闭]
【发布时间】:2013-02-16 11:14:37
【问题描述】:

我正在将我的服务器从 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(); 创建一个文件一样,它可以正常工作。

任何帮助将不胜感激。

【问题讨论】:

    标签: php apache .htaccess nginx front-controller


    【解决方案1】:

    这就是我将所有内容路由到 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
    

    【讨论】:

    • 这个 corse 允许任何现有文件,例如图像或其他 php 文件返回...它将任何未处理的请求路由到 index.php。
    • 谢谢,try_files $uri $uri/ /index.php?$args; 工作愉快!
    • +1 用于使用 try_files 而不是 if
    • 您的重点是错误的:这就是我将所有内容路由到 index.php 的方式,您允许不路由现有文件。我正在寻找将所有内容路由到前端控制器。您应该更新您的答案,添加此类示例或按照@Applehat 的建议进行更新。
    【解决方案2】:

    跳过正则表达式的结尾:

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

    【讨论】:

    • 不完全确定这里发生了什么。我更改了正则表达式以匹配该答案,但 nginx 仍然向我抛出 PHP 的源代码。为什么fastcgi_pass 在那个位置块中?不应该在~ \.php$下吗?
    • 它来自我的配置,每个位置都有不同的规则。奇怪。
    • 我不是 Nginx 方面的专家,所以你的猜测和我的一样好。 :p
    • 也许这会有所帮助:askubuntu.com/questions/134666/…
    猜你喜欢
    • 2012-03-30
    • 2020-04-16
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    • 2012-04-15
    • 2017-02-21
    • 2018-10-26
    • 2014-03-06
    相关资源
    最近更新 更多