Integrating with PHP-FPM and FastCGI
In this lesson, we'll explore how Nginx integrates with PHP applications through PHP-FPM (FastCGI Process Manager) and the FastCGI protocol. You'll learn to configure Nginx to process PHP files efficiently and securely.
Learning Objectives
By the end of this lesson, you will be able to:
- Understand the role of PHP-FPM and FastCGI in PHP processing
- Configure Nginx to pass PHP requests to PHP-FPM
- Set up proper security headers and file handling
- Troubleshoot common PHP-FPM integration issues
Understanding PHP-FPM and FastCGI
PHP-FPM is a PHP FastCGI implementation with additional features for heavy-loaded sites. FastCGI is a protocol for interfacing interactive programs with web servers, providing better performance than traditional CGI.
When a user requests a PHP file:
- Nginx receives the request
- Nginx passes the request to PHP-FPM via FastCGI protocol
- PHP-FPM processes the PHP code
- PHP-FPM returns the generated HTML to Nginx
- Nginx sends the response to the client
Basic PHP-FPM Configuration
Let's start with a basic Nginx configuration for PHP processing:
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
Always use Unix sockets for PHP-FPM communication when both services run on the same server. They're faster and more secure than TCP connections.
Complete PHP-FPM Setup
Here's a more comprehensive configuration with security considerations:
server {
listen 443 ssl http2;
server_name app.example.com;
root /var/www/app/public;
# SSL configuration (covered in previous lessons)
ssl_certificate /etc/ssl/certs/app.example.com.crt;
ssl_certificate_key /etc/ssl/private/app.example.com.key;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
try_files $uri =404;
include fastcgi_params;
# PHP-FPM socket
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
# Essential FastCGI parameters
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
# Security headers
fastcgi_hide_header X-Powered-By;
fastcgi_param HTTP_PROXY "";
# Timeouts
fastcgi_read_timeout 60s;
fastcgi_connect_timeout 60s;
fastcgi_send_timeout 60s;
# Buffer settings
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
}
# Deny access to sensitive files
location ~ /\.(ht|git|env) {
deny all;
return 404;
}
}
PHP-FPM Pool Configuration
PHP-FPM uses pools to manage worker processes. Here's a typical pool configuration:
[www]
user = www-data
group = www-data
listen = /var/run/php/php8.1-fpm.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 500
php_admin_value[upload_max_filesize] = 32M
php_admin_value[post_max_size] = 32M
php_admin_value[max_execution_time] = 30
Advanced FastCGI Caching
For high-traffic PHP applications, consider implementing FastCGI caching:
# Define cache zone
fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=phpcache:100m inactive=60m;
server {
# ... other server configuration
location ~ \.php$ {
# ... existing PHP configuration
# Cache configuration
fastcgi_cache phpcache;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
fastcgi_cache_valid 200 301 302 10m;
fastcgi_cache_valid 404 1m;
fastcgi_cache_use_stale error timeout updating http_500 http_503;
fastcgi_cache_background_update on;
add_header X-Cache $upstream_cache_status;
}
}
FastCGI caching is powerful but can cause issues with dynamic content. Always test thoroughly and consider excluding authenticated user pages from caching.
Health Checking and Monitoring
Set up health checks for your PHP-FPM backend:
location ~ ^/(status|ping)$ {
access_log off;
allow 127.0.0.1;
allow 192.168.1.0/24;
deny all;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
}
Common Pitfalls
- File Permission Issues: Ensure Nginx and PHP-FPM users have appropriate permissions to read files and write to necessary directories
- SCRIPT_FILENAME Missing: Forgetting to set
fastcgi_param SCRIPT_FILENAMEis the most common cause of "File not found" errors - Socket Permission Problems: PHP-FPM socket must be accessible by the Nginx user with proper permissions (usually 660)
- Buffer Size Too Small: Large PHP responses may get truncated if FastCGI buffers are too small
- Path Info Vulnerabilities: Be careful with
PATH_INFOas it can be exploited if not properly validated - Timeout Mismatches: Ensure Nginx and PHP-FPM timeout settings are aligned to prevent premature connection closures
Summary
In this lesson, you learned how to integrate Nginx with PHP-FPM using the FastCGI protocol. We covered basic configuration, security considerations, performance optimization with caching, and monitoring setups. Proper PHP-FPM integration ensures your PHP applications run efficiently and securely behind Nginx.
Quiz
Nginx and PHP-FPM Integration
What is the primary advantage of using Unix sockets over TCP for PHP-FPM communication?