Running PHP code through PHP-FPM provides several advantages over traditional execution, including greater concurrency and security. In this article, I will explain how to configure it under Nginx/Gentoo.
First, we install the web server, in this case Nginx:
We create a test document to verify that the server is working correctly:
echo ‘Hello, world!’ > /var/www/localhost/htdocs/index.html
We start the server:
rc-update add nginx default
We make a test request:
We compile PHP with the necessary use flags:
echo “app-eselect/eselect-php fpm” » /etc/portage/package.use/php
We compile PHP:
We adjust the FPM socket path and the user it will run with:
listen = /run/php-fpm.socket
listen.owner = nginx
The final configuration for the FPM pool is as follows:
[www]
user = nobody
group = nobody
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3
listen = /run/php-fpm.socket
listen.owner = nginx
We adjust the PHP timezone:
date.timezone = Europe/Madrid
We start PHP-FPM:
rc-update add php-fpm default
We configure Nginx to use FPM:
server {
...
location ~ \.php$ {
# Test for non-existent scripts or throw a 404 error
# Without this line, nginx will blindly send any request ending in .php to php-fpm
try_files $uri =404;
include /etc/nginx/fastcgi.conf;
fastcgi_pass unix:/run/php-fpm.socket;
}
}
We restart the service:
We generate a test php file:
We check that it works:
We delete the file to avoid problems:
The entire Nginx configuration would be as follows:
user nginx nginx;
worker_processes 1;
error_log /var/log/nginx/error_log info;
events {
worker_connections 1024;
use epoll;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main
'$remote_addr - $remote_user [$time_local] '
'"$request" $status $bytes_sent '
'"$http_referer" "$http_user_agent" '
'"$gzip_ratio"';
client_header_timeout 10m;
client_body_timeout 10m;
send_timeout 10m;
connection_pool_size 256;
client_header_buffer_size 1k;
large_client_header_buffers 4 2k;
request_pool_size 4k;
gzip off;
output_buffers 1 32k;
postpone_output 1460;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 75 20;
ignore_invalid_headers on;
index index.html;
server {
listen 80;
server_name localhost;
access_log /var/log/nginx/localhost.access_log main;
error_log /var/log/nginx/localhost.error_log info;
root /var/www/localhost/htdocs;
location ~ \.php$ {
try_files $uri =404;
include /etc/nginx/fastcgi.conf;
fastcgi_pass unix:/run/php-fpm.socket;
}
}
}
We restart the service: