'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. In nginx/FastCGI however, this doesn't work due to the way nginx works (by default).

Is it possible to make this work on nginx/FastCGI, and if so, how?



Solution 1:[1]

Easy solution:

fastcgi_keep_conn on; # < solution

proxy_buffering off;
gzip off;

Solution 2:[2]

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.

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.

Solution 3:[3]

Add the flush() function in your loop:

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

It might work, but not necessarily on each iteration (there's some magic involved!)

Solution 4:[4]

Solution 5:[5]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ondrej Prochazka
Solution 2 Redzarf
Solution 3 Parallelis
Solution 4 Baronth
Solution 5 n.r.