WordPress Proxy Pass Example

4.x is outdated, please check the latest version 22.x


Latest version: pecl install openswoole-22.1.2

We can use the Swoole\Coroutine\FastCGI\Proxy class to perform a proxy pass between a Swoole HTTP Server and a WordPress application using a PHP-FPM setup with FastCGI. This is made possible because the proxy pass class uses the Swoole request and response server objects, translates everything and communicates with PHP-FPM using the FastCGI Client, and then finally sending back the response.

By setting up a proxy pass and using the Swoole HTTP Server we can take advantage of the scalability and high performance of a Swoole server but still use a traditional WordPress setup. For this to work we have put the Swoole server in BASE mode which is where a worker handles a connection during its lifetime, not sharing itself with other connections, which is perfect for how PHP-FPM works.

use Swoole\Constant;
use Swoole\Http\Server;
use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\Coroutine\FastCGI\Proxy;

// WordPress project root directory on the server
$documentRoot = '/var/www/html';

/*
 * The port here needs to be consistent with the WordPress configuration. Generally, the port is not      * specified, but usually is port 80.
 */
$server = new Swoole\Http\Server('0.0.0.0', 80, SWOOLE_BASE);

$server->set([
    Constant::OPTION_WORKER_NUM => swoole_cpu_num() * 2,
    Constant::OPTION_HTTP_PARSE_COOKIE => false,
    Constant::OPTION_HTTP_PARSE_POST => false,
    Constant::OPTION_DOCUMENT_ROOT => $documentRoot,
    Constant::OPTION_ENABLE_STATIC_HANDLER => true,

    // WordPress static resource paths
    Constant::OPTION_STATIC_HANDLER_LOCATIONS => ['/wp-admin', '/wp-content', '/wp-includes'],
]);

// Create a new proxy object used to transfer request from Swoole to the FastCGI FPM server
$fpmProxy = new Swoole\Coroutine\FastCGI\Proxy('127.0.0.1:9000', $documentRoot);

// Every HTTP request is handled by Swoole but passed over to PHP-FPM to execute
$server->on('Request', function(Swoole\Http\Request $request, Swoole\Http\Response $response) use ($fpmProxy)
{
    // Actual proxy transfer from Swoole HTTP Server to the PHP FPM Server
    $fpmProxy->pass($request, $response);
});

$server->start();

Here the Swoole HTTP Server request and response objects are passed to the proxy pass method, internally this proxy uses the Swoole FastCGI client to communicate with the WordPress site using the FastCGI protocol, then handling the response from PHP-FPM and finally sending back the response to the original client which connected to the Swoole HTTP server.

Last updated on August 31, 2022