Httpd – Forwarding PHP requests via ProxyPassMatch as a handler, or only when file exists

apache-2.2fcgihttpdphp-fpmproxypass

I am migrating my server to use mod_proxy_fcgi and php-fpm instead of mod_php. Apache is able to forward .php requests to the fcgi proxy and PHP executes correctly. I've got this working with:

ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9000/var/www/html/$1

Unfortunately, Apache forwards all .php requests to the proxy, even when the file doesn't exist. This causes a few problems. My ErrorDocument rule isn't invoked, and DirectoryIndex index.php index.html doesn't fall back to index.html.

I was able to fix these problems with mod_rewrite:

RewriteEngine On                                                           
RewriteCond %{REQUEST_FILENAME} ^/((.*\.php)(/.*)?)$                       
RewriteCond /var/www/html/%2 -f                                   
RewriteRule . fcgi://127.0.0.1:9000/var/www/html/%1 [P] 

However, the Apache documentation does not recommend RewriteRule: "This is because this flag triggers the use of the default worker, which does not handle connection pooling."

Ideally, I think I'd either like to use ProxyPass in a FilesMatch block (currently unsupported), or define a new handler that proxies through fcgi and use it to handle .php requests, similar to what mod_php does.

Any suggestions for simulating a standard mod_php setup but actually proxying through fcgi?

Best Answer

One option is to install mod_proxy_handler: https://gist.github.com/progandy/6ed4eeea60f6277c3e39

Or you can wait for Apache 2.4.10, which should include the module.

Basically the module lets you do this:

#tcp
<FilesMatch \.php$>
SetHandler proxy:fcgi://localhost:9000
</FilesMatch>

#uds
<FilesMatch \.php$>
    SetHandler "proxy:unix:/path/to/socket.sock|fcgi://./"
</FilesMatch>
Related Topic