简体   繁体   English

如何在 nginx 中为 PHP 应用程序禁用输出缓冲

[英]How to disable output buffering in nginx for PHP application

We have code similar to this:我们有类似的代码:

<?php
    ob_implicit_flush(true);
    ob_end_flush();

    foreach ($arrayOfStrings as $string) {
        echo time_expensive_function($string);
    }
?>

In Apache, this would send each echo to the browser as it was output.在 Apache 中,这会在输出时将每个回显发送到浏览器。 In nginx/FastCGI however, this doesn't work due tot he way nginx works (by default).然而,在 nginx/FastCGI 中,由于 nginx 的工作方式(默认情况下),这不起作用。

Is it possible to make this work on nginx/FastCGI, and if so, how?是否可以在 nginx/FastCGI 上进行这项工作,如果可以,如何进行?

First php has to correctly flush everything :首先 php 必须正确刷新所有内容:

@ob_end_flush();
@flush();

Then, I found two working solutions:然后,我找到了两个可行的解决方案:

1) Via Nginx configuration: 1)通过Nginx配置:

fastcgi_buffering off;

2) Via HTTP header in the php code 2) 通过 php 代码中的 HTTP 标头

header('X-Accel-Buffering: no');

Easy solution:简单的解决方案:

fastcgi_keep_conn on; # < solution

proxy_buffering off;
gzip off;

I didn't want to have to turn off gzip for the whole server or a whole directory, just for a few scripts, in a few specific cases.在一些特定情况下,我不想为整个服务器或整个目录关闭 gzip,只为几个脚本关闭。

All you need is this before anything is echo'ed:在回显任何内容之前,您只需要这个:

header('Content-Encoding: none;');

Then do the flush as normal:然后照常进行冲洗:

ob_end_flush();
flush();

Nginx seems to pick up on the encoding having been turned off and doesn't gzip. Nginx 似乎接受了已关闭的编码并且不进行 gzip。

Add the flush() function in your loop:在循环中添加 flush() 函数:

foreach ($arrayOfStrings as $string) {
  echo time_expensive_function($string);
  flush();
}

It might work, but not necessarily on each iteration (there's some magic involved!)它可能有效,但不一定在每次迭代中都有效(这涉及到一些魔法!)

I needed both of those two lines at the beginning of my script:我在脚本的开头需要这两行:

header('X-Accel-Buffering: no');
ob_implicit_flush(true);

Each line alone would also work, combining them makes my browser getting the result from the server even faster.单独的每一行也可以工作,将它们组合起来可以让我的浏览器更快地从服务器获取结果。 Cannot explain it, just experienced it.无法解释,只是经历了。

My configuration is nginx with php-fpm.我的配置是带有 php-fpm 的 nginx。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM