diff --git a/includes/common.inc b/includes/common.inc
index c684d41..5ee8973 100644
--- a/includes/common.inc
+++ b/includes/common.inc
@@ -2609,8 +2609,28 @@ function drupal_page_footer() {
   if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
     drupal_serve_page_from_cache($cache);
   }
+
+  if (function_exists('fastcgi_finish_request')) {
+    // In PHP-FPM environements, detaching the process will close the gateway
+    // connection and ensure that all buffers are flushed, we then have no need
+    // for further output buffer handling.
+    fastcgi_finish_request();
+  }
   else {
-    ob_flush();
+    // This listener will be run in all cases, including when sending an HTTP
+    // redirect code. In this particular case, PHP output buffer has not been
+    // initialized yet and won't be, calling the ob_end_flush() method would
+    // throw PHP warnings.
+    // See http://www.php.net/manual/en/function.ob-end-flush.php#42979
+    while (ob_get_level() > 0) {
+      // Using ob_end_flush() instead of ob_flush() will close the output
+      // buffer. This means that potential later errors won't get to the user.
+      // Flushing the buffers followed by the flush() call will force buffers
+      // to be pushed upper layer (HTTPd or CGI gateway) allowing it to send
+      // it to the client faster.
+      // See http://drupal.org/node/1651010#comment-6180946 for details.
+      ob_end_flush();
+    }
   }
 
   _registry_check_code(REGISTRY_WRITE_LOOKUP_CACHE);
