Back to Blog
Nginx Performance Tuning for Laravel Applications
Nginx as Laravel's Gateway
Nginx is the first point of contact for requests to your Laravel application. Proper tuning can significantly improve performance and handle higher loads.
Worker Configuration
# /etc/nginx/nginx.conf
# One worker per CPU core
worker_processes auto;
events {
worker_connections 4096;
use epoll;
multi_accept on;
}
http {
# Buffers
client_body_buffer_size 10K;
client_header_buffer_size 1k;
client_max_body_size 50M;
large_client_header_buffers 2 1k;
# Timeouts
client_body_timeout 12;
client_header_timeout 12;
keepalive_timeout 65;
send_timeout 10;
}
Compression
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml application/json
application/javascript application/xml+rss
application/atom+xml image/svg+xml;
Static Asset Caching
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2)$ {
expires 1y;
add_header Cache-Control "public, immutable";
access_log off;
}
FastCGI Caching
# Define cache zone
fastcgi_cache_path /var/cache/nginx levels=1:2
keys_zone=LARAVEL:100m inactive=60m;
server {
location ~ \.php$ {
fastcgi_cache LARAVEL;
fastcgi_cache_valid 200 60m;
fastcgi_cache_bypass $http_pragma;
fastcgi_cache_revalidate on;
add_header X-Cache-Status $upstream_cache_status;
}
}
PHP-FPM Configuration
# /etc/php/8.3/fpm/pool.d/www.conf
pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
pm.max_requests = 500
# Socket connection (faster than TCP)
listen = /run/php/php8.3-fpm.sock
Load Balancing
upstream laravel {
least_conn;
server 10.0.0.1:9000 weight=5;
server 10.0.0.2:9000 weight=5;
keepalive 32;
}
Conclusion
Nginx tuning involves worker optimization, compression, caching, and PHP-FPM configuration. Test changes under load and monitor the impact.
Related Articles
Need Help With Your Project?
I respond to all inquiries within 24 hours. Let's discuss how I can help build your production-ready system.
Get In Touch