SlideShare a Scribd company logo
Boost your website by running
PHP on Nginx
Tips and tricks for high performance websites
Harald Zeitlhofer @HZeitlhofer
harald.zeitlhofer@dynatrace.com
Harald Zeitlhofer
• Technology Strategist at Dynatrace
• Database and Web Development
• Love to discover new things
Tips and tricks for high performance websites
Once upon a time...
performance matters !!!
performance matters !!!
performance matters !!!
Boost your website by running PHP on Nginx
Boost your website by running PHP on Nginx
Modern Web Pages: lots of static content
434 Resources in total on that page:
230 JPEGs, 75 PNGs, 50 GIFs, …
more than 20MB page size
Fifa.com during Worldcup 2014
http://blog.dynatrace.com/2014/05/21/is-the-fifa-world-cup-website-ready-for-the-tournament/
largest item on page:
favicon.ico with 370 KB!!!
but also some heavyweight
CSS and JS files with up to 288 KB!!!
• Expires
• Last-Modified
• Etag
• Cache-Control
cached content
can still create roundtrips
to the network!
Web Request handling
Web Request handling
PHP-FPM
FastCGI Process Manager
Available since 5.3.3
Stable since 5.4.1
PHP-FPM
• Installation
• Pool configuration
/etc/php/7.0/fpm/pool.d/www.conf
[www]
user = www-data
group = www-data
listen = 127.0.0.1:9000# for Unix socket: unix:/var/run/php7.0-fpm.sock;
root@hzvm01:/etc/nginx/sites-enabled# ps -ef | grep php
root 6435 1 0 14:39 ? 00:00:32 php-fpm: master process (/etc/php/7.0/fpm/php-fpm.conf)
spelix 6439 6435 0 14:39 ? 00:00:00 php-fpm: pool batch
spelix 6440 6435 0 14:39 ? 00:00:00 php-fpm: pool batch
www-data 10576 6435 1 18:45 ? 00:00:48 php-fpm: pool www
www-data 10920 6435 1 18:47 ? 00:00:47 php-fpm: pool www
www-data 10927 6435 1 18:47 ? 00:00:46 php-fpm: pool www
sudo apt-get install php7.0-fpm
Nginx
Lightweight HTTP server
Event based request handling
Open Source project (BSD)
Development started in 2002 by Igor Sysoev to solve the c10k problem
Commercial version NGINX Plus
Leading among
top 100.000 websites
/etc/nginx/nginx.conf
# max_clients = worker_processes * worker_connections
worker_processes 8; # number of CPUs
pcre_jit on; # enable JIT for regex
events {
worker_connections 1024;
multi_accept on;
}
Integration
• Static content served by Nginx
• Dynamic requests sent to PHP
server {
listen 80;
server_name www.yourdomain.com;
root /var/www/test;
index index.php index.html index.htm;
location ~* .(html|js|css|gif|jpg|jpe|jpeg|png|bmp|tif|pdf|ico)$ {
try_files $uri =404;
}
location / {
try_files $uri $uri/ =404;
}
location ~* .php$ {
fastcgi_index index.php;
fastcgi_pass 127.0.0.1:9000;
include fastcgi_params;
}
}
Communication via sockets
• TCP vs Unix
• Unix slightly faster when used on localhost
• Use TCP for high load
location ~* .php$ {
fastcgi_index index.php;
fastcgi_pass 127.0.0.1:9000;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
}
fastcgi_pass unix:/var/run/php7.0-fpm.sock;
Transaction flow
URL rewrite
...
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.+)$ index.php
...
http://www.mysite.com/news/browse/2014
 to be processed by index.php
URL rewrite
server {
listen 80;
root /var/www;
index index.php index.html index.htm;
server_name www.mysite.com;
location / {
try_files $uri $uri/ @missing;
}
location @missing {
rewrite (.*) /index.php;
}
location ~ .php$ {
fastcgi_index index.php;
include fastcgi_params;
fastcgi_pass unix:/var/run/php5-fpm.sock;
}
}
http://www.mysite.com/news/browse/2014
 to be processed by index.php
URL rewrite
using Nginx/PHP-FPM there’s a better way:
server {
listen 80;
root /var/www;
index index.php index.html index.htm;
server_name www.mysite.com;
location /images {
try_files $uri =404;
}
location /scripts {
try_files $uri =404;
}
location / {
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME /var/www/index.php;
fastcgi_pass unix:/var/run/php5-fpm.sock;
}
}
<?php
$params = explode('/', $_SERVER["DOCUMENT_URI"]);
...
Finish Web Request
<?php
do_some_processing();
render_page();
fastcgi_finish_request();
do_slower_stuff(Array(
‘convert_uploaded_videos’,
‘post_to_social_media_platforms’,
‘backup_data’,
‘much more’
));
?>
Nginx and Caching
Nginx FastCGI cache
• Part of Nginx' FastCGI module
fastcgi_cache_path /etc/nginx/cache levels=1:2 keys_zone=APPKEY:100m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
location ~* .php$ {
fastcgi_index index.php;
fastcgi_pass 127.0.0.1:9000;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_cache APPKEY;
fastcgi_cache_valid 200 60m;
}
FastCGI cache in action
<?php
echo time()."n";
?>
FastCGI cache in action
<?php
echo time()."n";
?>
FastCGI cache in action
<?php
echo time()."n";
?>
Full page cache with Memcached
<?php
...
function __construct () {
$this->c = new Memcached();
$this->c->addServer('localhost',11211);
}
function setCache ($key, $content) {
$this->c->set($key, $content);
}
...
// get HTML content
$html = $this->renderPage();
$this->setCache($_SERVER['REQUEST_URI'], $html);
echo $html;
...
?>
Data cache with Memcached
<?php
...
function __construct () {
$this->c = new Memcached();
$this->c->addServer('localhost',11211);
}
function setCache ($key, $content) {
$this->c->set($key, $content);
}
...
// get data structure
$newslist = $this->getNewsList();
$this->setCache('/data/news/getlist', json_encode($newslist));
...
?>
Full page / data cache with Nginx and Memcached
• ngx_http_memcached_module
server {
location / {
set $memcached_key "$uri";
memcached_pass localhost:11211;
error_page 404 502 504 = @notincache;
}
location @notincache {
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
}
PHP, 5k requests, concurrency 100
0
1
2
3
4
5
6
7
8
Apache+PHP Nginx+PHP Nginx+Memcached
<?php
echo "Hello World";
?>
7,28 4,6 3,05
totaltimeinsec
Caching Static Content
• set HTTP response expires header
location ~ .(html|js|css|gif|jpg|jpe|jpeg|png|bmp|tif|pdf|ico)$ {
expires 365d;
access_log off;
error_log off;
log_not_found off;
add_header Cache-Control "public";
try_files $uri =404;
}
Filehandle Caching
• keep handlers for requested static files open
open_file_cache max=1000 inactive=5m;
open_file_cache_valid 60s;
open_file_cache_min_uses 5;
open_file_cache_errors off;
FastCGI request forwarding
server {
listen 80;
root /var/www/mysite;
server_name www.mysite.com;
location / {
try_files $uri =405;
}
location ~ .php$ {
fastcgi_pass 192.168.56.12:9000;
fastcgi_index index.php;
include fastcgi_params;
}
}
FastCGI request forwarding
upstream php {
server 192.168.56.12:9000;
}
server {
listen 80;
root /var/www/mysite;
server_name www.mysite.com;
location / {
try_files $uri =405;
}
location ~ .php$ {
fastcgi_pass php;
fastcgi_index index.php;
include fastcgi_params;
}
}
Load balancing
upstream php {
ip_hash;
server unix:/var/run/php5-fpm.sock weight=5;
server 192.168.56.12:9000 weight=2;
server 192.168.56.13:9000;
server 192.168.56.14:9000 backup;
}
server {
listen 80;
root /var/www/mysite;
server_name www.mysite.com;
location / {
try_files $uri =405;
}
location ~ .php$ {
fastcgi_pass php;
fastcgi_index index.php;
include fastcgi_params;
}
}
High scalability
Boost your website by running PHP on Nginx
Boost your website by running PHP on Nginx
desktop traffic
response time
slow response time
traffic using chrome
Boost your website by running PHP on Nginx
Boost your website by running PHP on Nginx
Boost your website by running PHP on Nginx
Boost your website by running PHP on Nginx
Boost your website by running PHP on Nginx
Boost your website by running PHP on Nginx
My favorite performance tools
• Load Generator (Apache Benchmark, Selenium, JMeter)
• Firebug, Google Developer Tools
• Dynatrace Application Monitoring Free Trial
• Free trial license for 30 days
• Free personal license for developers
• Dynatrace Ruxit
• 2016 free hours for monitoring
http://bit.ly/monitoring-2016
http://bit.ly/dttrial
Further information
http://apmblog.dynatrace.com
http://apmblog.dynatrace.com/2014/08/19/easily-boost-web-application-using-nginx/
http://apmblog.dynatrace.com/2014/10/30/proper-configuration-running-php-nginx/
http://apmblog.dynatrace.com/2015/11/24/cool-new-stuff-on-the-nginx-front/
https://www.nginx.com/resources/wiki/
Harald Zeitlhofer
Performance Advocate
@HZeitlhofer
harald.zeitlhofer@dynatrace.com
http://blog.dynatrace.com
Dynatrace Free Trial
Free Personal License
Ruxit Free Trial
http://bit.ly/monitoring-2016
events@dynatrace.com

More Related Content

PDF
Running PHP on Nginx
PDF
Slow Database in your PHP stack? Don't blame the DBA!
PDF
Improve Magento Performance
PDF
Scaling PHP web apps
PDF
PHP and databases
PDF
Running php on nginx
PPTX
PHP conference Berlin 2015: running PHP on Nginx
PDF
Caching with Memcached and APC
Running PHP on Nginx
Slow Database in your PHP stack? Don't blame the DBA!
Improve Magento Performance
Scaling PHP web apps
PHP and databases
Running php on nginx
PHP conference Berlin 2015: running PHP on Nginx
Caching with Memcached and APC

What's hot (18)

PDF
Background Tasks in Node - Evan Tahler, TaskRabbit
PPTX
Caching
PDF
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
PDF
Building Scalable Websites with Perl
PDF
Caching basics in PHP
PPT
Big data with hadoop Setup on Ubuntu 12.04
PDF
04 web optimization
PPTX
HBaseConEast2016: Practical Kerberos with Apache HBase
PDF
Introduction to performance tuning perl web applications
PDF
Nginx: Accelerate Rails, HTTP Tricks
PPTX
Using memcache to improve php performance
PDF
Query optimization: from 0 to 10 (and up to 5.7)
PPTX
Reverse proxy & web cache with NGINX, HAProxy and Varnish
PDF
NginX - good practices, tips and advanced techniques
PDF
Load Balancing with Nginx
PDF
Open Source Backup Conference 2014: Migration from bacula to bareos, by Danie...
PDF
PyGotham 2014 Introduction to Profiling
PPT
Memcache
Background Tasks in Node - Evan Tahler, TaskRabbit
Caching
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Building Scalable Websites with Perl
Caching basics in PHP
Big data with hadoop Setup on Ubuntu 12.04
04 web optimization
HBaseConEast2016: Practical Kerberos with Apache HBase
Introduction to performance tuning perl web applications
Nginx: Accelerate Rails, HTTP Tricks
Using memcache to improve php performance
Query optimization: from 0 to 10 (and up to 5.7)
Reverse proxy & web cache with NGINX, HAProxy and Varnish
NginX - good practices, tips and advanced techniques
Load Balancing with Nginx
Open Source Backup Conference 2014: Migration from bacula to bareos, by Danie...
PyGotham 2014 Introduction to Profiling
Memcache
Ad

Viewers also liked (20)

PDF
FEMTOprint Corporate Brochure
PDF
Performance optimisation - scaling a hobby project to serious business
DOCX
Jardas
PDF
Don’t Lose Your Caffeine Buzz to Cybercrime
PDF
Инвестиционная стратегия (Москва)
PDF
ASEE Metal Impingement paper 50 final
DOCX
Assure model day 3
PPTX
A Review of EnglishCentral (an online video-based material)
PDF
자료집 416특별법국민설명회 20140709
PDF
Procesadores
PDF
финансовый рынок _09(1)
PPTX
PPTX
политех
PPTX
Implications Enclosure and Privatization of the Commons on Women’s Access to ...
DOC
Double looplearning
DOCX
Belajar framework code igniter xii rpl
PPTX
մեր բնակավայրի հիմնախնդիրները
DOCX
Html dasar 123
PDF
IRM archiveDoc – электронный архив: система электронного хранения документов
PPT
Linking State and Non-State Justice Systems in Afghanistan
FEMTOprint Corporate Brochure
Performance optimisation - scaling a hobby project to serious business
Jardas
Don’t Lose Your Caffeine Buzz to Cybercrime
Инвестиционная стратегия (Москва)
ASEE Metal Impingement paper 50 final
Assure model day 3
A Review of EnglishCentral (an online video-based material)
자료집 416특별법국민설명회 20140709
Procesadores
финансовый рынок _09(1)
политех
Implications Enclosure and Privatization of the Commons on Women’s Access to ...
Double looplearning
Belajar framework code igniter xii rpl
մեր բնակավայրի հիմնախնդիրները
Html dasar 123
IRM archiveDoc – электронный архив: система электронного хранения документов
Linking State and Non-State Justice Systems in Afghanistan
Ad

Similar to Boost your website by running PHP on Nginx (20)

PDF
Nginx pres
PDF
Running PHP on nginx
PDF
Nginx, PHP, Apache and Spelix
PDF
Running PHP on Nginx / PHP wgtn
PDF
10 Million hits a day with WordPress using a $15 VPS
PDF
Deploying nginx with minimal system resources
PDF
Nginx Workshop Aftermath
ODP
Caching and tuning fun for high scalability
ODP
Caching and tuning fun for high scalability @ FOSDEM 2012
PPT
Roy foubister (hosting high traffic sites on a tight budget)
PDF
Scale Apache with Nginx
DOC
Nginx 0.8.x + php 5.2.13 (fast cgi) setup web server
PDF
Cluster Fudge: Recipes for WordPress in the Cloud (WordCamp Austin 2014 Speaker)
PDF
Cluster Fudge: Recipes for WordPress in the Cloud (WordCamp Austin 2014 Speaker)
PPTX
WordPress + NGINX Best Practices with EasyEngine
PDF
Magento's Imagine eCommerce Conference 2011 - Hosting Magento: Performance an...
PDF
Magento Imagine eCommerce Conference February 2011: Optimizing Magento For Pe...
PPTX
20151229 wnmp & phalcon micro app - part I
ODP
Caching and tuning fun for high scalability
Nginx pres
Running PHP on nginx
Nginx, PHP, Apache and Spelix
Running PHP on Nginx / PHP wgtn
10 Million hits a day with WordPress using a $15 VPS
Deploying nginx with minimal system resources
Nginx Workshop Aftermath
Caching and tuning fun for high scalability
Caching and tuning fun for high scalability @ FOSDEM 2012
Roy foubister (hosting high traffic sites on a tight budget)
Scale Apache with Nginx
Nginx 0.8.x + php 5.2.13 (fast cgi) setup web server
Cluster Fudge: Recipes for WordPress in the Cloud (WordCamp Austin 2014 Speaker)
Cluster Fudge: Recipes for WordPress in the Cloud (WordCamp Austin 2014 Speaker)
WordPress + NGINX Best Practices with EasyEngine
Magento's Imagine eCommerce Conference 2011 - Hosting Magento: Performance an...
Magento Imagine eCommerce Conference February 2011: Optimizing Magento For Pe...
20151229 wnmp & phalcon micro app - part I
Caching and tuning fun for high scalability

Recently uploaded (20)

PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Electronic commerce courselecture one. Pdf
PDF
Encapsulation theory and applications.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Empathic Computing: Creating Shared Understanding
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPT
Teaching material agriculture food technology
NewMind AI Weekly Chronicles - August'25 Week I
Diabetes mellitus diagnosis method based random forest with bat algorithm
Unlocking AI with Model Context Protocol (MCP)
Encapsulation_ Review paper, used for researhc scholars
Digital-Transformation-Roadmap-for-Companies.pptx
The AUB Centre for AI in Media Proposal.docx
Electronic commerce courselecture one. Pdf
Encapsulation theory and applications.pdf
20250228 LYD VKU AI Blended-Learning.pptx
NewMind AI Monthly Chronicles - July 2025
Reach Out and Touch Someone: Haptics and Empathic Computing
The Rise and Fall of 3GPP – Time for a Sabbatical?
Review of recent advances in non-invasive hemoglobin estimation
Empathic Computing: Creating Shared Understanding
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Building Integrated photovoltaic BIPV_UPV.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
MYSQL Presentation for SQL database connectivity
Dropbox Q2 2025 Financial Results & Investor Presentation
Teaching material agriculture food technology

Boost your website by running PHP on Nginx

Editor's Notes

  • #6: application performance. high performance web sites scalable cloud infrastructure flexible microservice architecture DBA: database tuning Sysop: webservers, caching servers, reverse proxies, load balancers migrated to nginx Developer: new frameworks
  • #13: 304 conditional caching with Entity Tag (E-Tag) header set