Tue 30 May 2006
After my first post about nginx web and reverse-proxy server, I have received many e-mail comments and questions. One of the most popular questions was “How to use PHP with nginx?”. This small howto-like article is about how to do it.
Nginx supports FastCGI technology to work with many external tools and servers. PHP itself can be runned as FastCGI application and can process FastCGI requests from nginx.
So, first of all we need to install PHP with fastcgi support and run it on some local tcp port. Installation process can go different ways, but I will describe here how to compile PHP from sources because it is generic way. To get fastcgi-enabled version of PHP interpreter, you may use following commands:
...
# make
...
# make install
...
#
When all of these commands will be completed, you will be able to run your fastcgi server. But there are two different ways to do it:
- Running PHP’s built-in FastCGI server - this method don’t require any third party tools.
- Running PHP inside some third-party wrapper - it can be more comfortable than first method because of more flexibility.
If you want to run PHP using its built-in FastCGI manager, you can use following script:
## ABSOLUTE path to the PHP binary
PHPFCGI="/opt/php/bin/php"
## tcp-port to bind on
FCGIPORT="8888"
## IP to bind on
FCGIADDR="127.0.0.1"
## number of PHP children to spawn
PHP_FCGI_CHILDREN=5
## number of request before php-process will be restarted
PHP_FCGI_MAX_REQUESTS=1000
# allowed environment variables sperated by spaces
ALLOWED_ENV="ORACLE_HOME PATH USER"
## if this script is run as root switch to the following user
USERID=www-data
################## no config below this line
if test x$PHP_FCGI_CHILDREN = x; then
PHP_FCGI_CHILDREN=5
fi
ALLOWED_ENV="$ALLOWED_ENV PHP_FCGI_CHILDREN"
ALLOWED_ENV="$ALLOWED_ENV PHP_FCGI_MAX_REQUESTS"
ALLOWED_ENV="$ALLOWED_ENV FCGI_WEB_SERVER_ADDRS"
if test x$UID = x0; then
EX="/bin/su -m -c \"$PHPFCGI -q -b $FCGIADDR:$FCGIPORT\" $USERID"
else
EX="$PHPFCGI -b $FCGIADDR:$FCGIPORT"
fi
echo $EX
# copy the allowed environment variables
E=
for i in $ALLOWED_ENV; do
E="$E $i=${!i}"
done
# clean environment and set up a new one
nohup env - $E sh -c "$EX" &> /dev/null &
If you want to use third party software to start PHP as FastCGI-server,you can take a look at spawn-fcgi from Lighttpd project.
So, your PHP FastCGI server has been started and now last thing you need to do is to configure nginx server to forward php-requests to PHP’s tcp-port. It can be done with following config file snipet (full version is here):
#
location ~ .php$ {
fastcgi_pass 127.0.0.1:8888;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /usr/local/nginx/html$fastcgi_script_name;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
}
That is all! Now you can use your nginx to serve any PHP-enabled sites and its performance will be very close to Apache mod_php module, but you will get more memory to process more requests from your site visitors.
As always, if you have some questions or suggestions, you can post them in comments area or email me. If you like this article, please vote for it on digg.com.
- Typical Configurations Overview For Nginx HTTP(S) Reverse Proxy/Web Server
- Compiling nginx in RedHat Linux: PCRE library problem
- Monitoring nginx Server Statistics With rrdtool
- Nginx - Small, But Very Powerful and Efficient Web Server
- Flash Video (FLV) Streaming With Nginx

2006-05-31 at 8.07 pm
[...] Monitoring nginx Server Statistics With rrdtoolNginx - Small, But Very Powerful and Efficient Web ServerNginx With PHP As FastCGI HowtoUsing epoll() For Asynchronous Network Programming [...]
2006-06-01 at 6.58 am
После компиляции у PHP 5.1.4 не появился ключ -b.
2006-06-08 at 1.55 pm
Грабли.
1. PHP запущенный с ключем “-b” время от времени незаметно падает. Как решить не знаю.
2. Для нормальной работы скриптов типа “Dumper” или других длинных скриптов можно использовать
fastcgi_read_timeout 10m; например.
Макс Тараненко.
2006-07-02 at 5.06 pm
Привет,
Я с ним (nginx) первый раз столкнулся. Замучился уже с настройкой rewrite+php (fastcgi). Могли бы показать?
Мне надо сдлелать “разброску” по поддоменам (это я уже решил) так, чтоб это нормально работало с PHP (это и есть проблема).
Проблема заключается в том, что в ответ на http://SOME.localhost.ru/ я получаю то, что требуется, а в ответ на http://SOME.localhost.ru/index.php получаю сообщение “No input file specified”, т.е. я неверно настроил реврайтинг.
Вот мой конфиг:
server {
listen 127.0.0.1:80;
server_name localhost.ru *.localhost.ru
location / {
root /home/www/data/public_html/;
index index.php index.html index.htm;
# перенаправление YYY.XXX.localhost.ru на XXX.localhost.ru
if ($http_host ~ ^.+\.[^\.]+\.localhost\.ru.*$) {
rewrite ^(.*)$ $http_host$1;
rewrite ^.*\.([^\.]+)\.localhost\.ru(.*)$ http://1.localhost.ru2 permanent;
break;
}
# отображение XXX.localhost.ru в пользовательские папки XXX
if ($http_host ~ ^.*\.localhost\.ru.*$) {
rewrite ^(.*)$ $http_host$1;
rewrite ^(.+)\.localhost\.ru(.*)$ /ub$2 break;
break;
}
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /home/flybb/data/public_html$fastcgi_script_name;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
}
}
2006-08-24 at 7.00 pm
Добрый день.
Осмелюсь задать вопрос и расчитываю на помощь, так как не у кого больше спросить
Есть виртуальный сервер, в котором нужно прописать alias - выглядит это так:
location / {
root /www/www2/www3/forum ;
index index.php;
}
location ~ \.php$ {
fastcgi_pass unix:/tmp/php4.3.0-fcgi.sock;
#fastcgi_pass 127.0.0.1:9090;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /www/www2/www3/forum$fastcgi_script_name;
fastcgi_param QUERY_STRING $query_string;
}
и нужно добавить алиас который будет обрабатываться PHP-шником:
location /gallery/ {
alias /www/www2/www3/4images/;
index index.php;
}
И вот не получается
Статику из алиаса отдаёт, а ПХП скрипты нет 
Подскажите что нужно сделать. Заранее благодарен.
Вид сайта должен получиться таким:
http://www.site.com/
а с алисом
http://www.site.com/gallery/
2006-08-24 at 7.19 pm
А почему алиас, а не просто root?
2006-08-25 at 3.18 pm
Hi, I am relitavely new to nginx and I was wondering how to add multiple servers/vhosts. DO I just add another server declaration?
2006-08-25 at 3.23 pm
Yes, just add another server section with different hostname.
2006-08-25 at 3.36 pm
Cool, thanks!
2006-08-25 at 4.24 pm
[...] nginx and Php/Fastcgi [...]
2006-08-26 at 9.24 pm
а можно ли как то задавать отдельным виртуальным серверам разные значения php_flag?
2006-08-26 at 10.23 pm
Я думаю, что только проксируя из них на отдельные fastcgi-сервера с разными конфигами…. насколько мне известно, php не умеет принимать такие параметры из fastcgi.
2006-10-13 at 3.23 pm
Форум IPB под fastcgi php не хочет показывать IP посетителя. Вместо него ставит -1
Подскажите в чем может быть дело.
2006-10-13 at 5.03 pm
Дело может юыть в том, что он пытается брать IP юзера из какого-то хитрого места… я вижу 2 варианта:
1) Попатчить его
2) Найти, как он это делает и попытаться передать ему этот IP нужным образом.
2006-11-15 at 9.38 pm
Is there a nginx mailing list or forum? I feel bad always asking you these questions before I try and switch our site from lighttpd to nginx.
But on that note…
The nginx site mentions “quick log rotation” but I can’t seem to find anything on it. I pipe apache and lighttpd logs through cronolog right now. Can nginx do that and if so, what would the syntax be?
2006-11-15 at 10.08 pm
2Ian: http://wiki.codemongers.com/ - great resource about Nginx.
Nginx community is primarily Russian speaking now, so it can be hard to ask community some questions…
But don’t think, that there is no English-speaking community! It is there, but it is not so organized yet as Russian one is, so there is no active newsgroups or mailing lists dedicated to nginx. But you can as me here or via IM and I’ll try to answer within my knowledge of nginx and English
2007-01-02 at 4.27 pm
Could anyone tell me how to add multiple servers/vhosts?
2007-02-12 at 10.45 pm
[...] La pulce nell’orecchio su Nginx me l’aveva messa un commento in un post letto qualche tempo fa. Per chi non conoscesse Nginx basta dire che è un web server utilizzato da moltissimi siti russi ad alto traffico, è leggerissimo e sicuro. E’ ideale per servire grandi quantità di immagini o file statici e può essere usato anche come reverse-proxy per allegerire il carico di Apache. Per ora l’ho compilato lasciando le impostazioni di default su Slackware e sto facendo solo qualche test. Per chi fosse interessato a far girare anche script php in Nginx ho trovato un howto ben fatto Nginx With PHP As FastCGI Howto. [...]
2007-02-26 at 9.53 pm
Nginx seems very tempting/interesting piece of software. Does anybody know how it how it performs on dual/multiple processor machines?
Regards, Clau
2007-02-26 at 10.33 pm
2dclau: It performs really well because it has set of worker processes each of them implements connections multiplexing with asynchronous sockets and FSM. You really should try it.
2007-02-27 at 1.49 pm
I will.
Regards, Clau
2007-03-06 at 1.12 pm
Ребята, помогите с решением проблемы.
Переходим с Apache на Nginx, производительность возросла в Х-раз, ресурсов жрет ровно в 2 раза меньше, в общем все летает, но есть одна проблемка из-за которой перейти не можем.
В Apache .htaccess есть правило
RewriteCond %{REMOTE_ADDR} ^XXX.XXX.XXX.XXX
RewriteRule ^(.*)folder/([0-9]*).gif$ http://othersite.com//2.gif
RewriteCond %{REMOTE_ADDR} !^XXX.XXX.XXX.XXX
RewriteRule ^(.*)folder/([0-9]*).gif$ http://mainsite.com//2.gif
Помогите написать такие правила для Nginx
Спасибо.
2007-03-06 at 4.05 pm
http://sysoev.ru/nginx/docs/http/ngx_http_rewrite_module.html
2007-03-26 at 8.40 am
After the first time I launch my info.php for test, I have this message :
“No input file specified.”
Could anybody help me ?
Jeremy.
2007-03-27 at 9.25 am
For Jeremy:
That error means that the path at:
fastcgi_param SCRIPT_FILENAME /usr/local/nginx/html$fastcgi_script_name;
Doesn’t point to your php files.
Regards
2007-03-30 at 8.41 am
во freebsd скрипт запуска php fcgi
строчку
EX=”/bin/su -m -c \”$PHPFCGI -q -b $FCGIADDR:$FCGIPORT\” $USERID”
надо заменить на
EX=”/bin/su -m $USERID -c \”$PHPFCGI -q -b $FCGIADDR:$FCGIPORT\”"
2007-03-31 at 6.35 am
Скрипт для запуска php в fastcgi работает нормально на 5.1.6 и не работает на 5.2.1. Получаю Connection from disallowed IP в stderr от php и закрытие соединения. Убираю параметр -q и всё работает на 5.2.1
2007-03-31 at 7.44 am
Хотя ошибся
установил FCGI_WEB_SERVER_ADDRS=”127.0.0.1″ и заработало.
2007-03-31 at 10.14 am
Thanks ! It works
Relative path “html$fastcgi_script_name;” doesn’t work…but…Absoulte path “/usr/local/nginx/html$fastcgi_script_name;” works
Regards
2007-04-02 at 2.21 pm
Nginx - это конечно здорово, но очень узкоспециализировано…
Кто-нить смог решить проблему использования файлов *.htc c этим сервером?
Кто хочет по настоящему “устать” - вперед…
Интересно, это вообще реально?
2007-04-30 at 3.04 pm
А в чём проблема с .htc?
2007-05-07 at 11.38 am
Hi
I installed nginx and php as you said but when I try to open a php file it displays:
The page you are looking for is temporarily unavailable.
Please try again later.
Can you help me with that?
Thanks
2007-05-25 at 5.51 pm
А вот fcgi во всех ли версиях пхп есть?
Очепяточку поправьте “версия примера нвходится”.
2007-06-06 at 6.41 am
Hello,
I have some problems with rewrite rules.
First, excuse me for my bad English…
I have an htacces from Apache like :
RewriteEngine on
DirectoryIndex gabarit.php?contenu=itineraire
RewriteCond %{REQUEST_URI} !temporaire\.htm
RewriteRule ^([a-z-]*)\.htm$ gabarit\.php?contenu=$1 [L]
RewriteRule ^galeries/$ gabarit\.php?contenu=accueil-galerie [L]
RewriteRule ^galeries/([0-9]*)/([0-9]*)\.htm$ gabarit\.php?contenu=detail-galerie&categorie=$1&galerie=$2 [L]
I want to translate it to Nginx rewrite rules
Here, a piece of my conf that doesn’t work :
location /
{
index gabarit.php;
root /home/work/jnbarak/current;
rewrite ^/(.*)\.htm$ /gabarit.php?contenu=$1 last; # it works !
rewrite ^/galeries/$ /gabarit\.php?contenu=accueil-galerie? last; # it doesn’t work !
rewrite ^/galeries/([0-9]*)/([0-9]*)\.htm$ /gabarit\.php?contenu=detail-galerie&categorie=$1&galerie=$2 last; # it doesn’t work !
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ \.php$
{
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /home/work/jnbarak/current$fastcgi_script_name;
include /usr/local/nginx/conf/fastcgi.conf;
}
When I try :
http://my_domain.tld/galeries/
I have the error :
“No input file specified.”
When I try :
http://my_domain.tld/galeries/1/5.htm
I am redirect to :
http://my_domain.tld/gabarit.php?contenu=accueil-galerie
Some one can help me please ?
Good job with this blog and long life to Nginx !
Jeremy.
2007-07-02 at 4.03 pm
Hello,
I want to deleguate the rewrite rules of my vhosts to an other person who hasn’t root privileges.
With Apache, it’s possible to declare a dynamic configuration file htaccess in each web repository. And it’s not necessary to restart the server when file has changed.
Is it possible to do it with Nginx ?
Best regards.
Jérémy.
2007-07-04 at 5.56 pm
To: toivo
> 1. PHP запущенный с ключем “-b” время от времени незаметно падает. Как решить не знаю.
Сталкнулся с такой же проблемой. Удалось решить?
2007-07-04 at 10.21 pm
2Dmitry:
> ## number of request before php-process
> will be restarted
> PHP_FCGI_MAX_REQUESTS=1000
Вот оно - решение
Падает он незаметно именно после 1000 запросов в данном случае. Потому надо перезапускать или найти как отключить (может быть при 0 оно не будет его гасить).
2007-07-09 at 6.13 pm
[...] the script here. Inspiration for this script came from Alexey N. Kovyrin. It has been modified only for Ubuntu’s PHP path. Don’t forget to put it into [...]
2007-09-12 at 8.28 pm
[...] Nginx With PHP As FastCGI Howto :: Homo-Adminus Blog by Alexey Kovyrin Nginx supports FastCGI technology to work with many external tools and servers. PHP itself can be runned as FastCGI application and can process FastCGI requests from nginx. (tags: deployment fastcgi httpd nginx performance php) [...]
2007-10-07 at 11.03 pm
Excellent tutorial Scoundrel. keep them coming.
2007-10-12 at 9.13 am
thanks
There’s a question I have to ask.
My php scripts are in /var/www/my/,so I created a alias for them.
Content:
location /my/
{
alias /vaw/www/my/;
}
After running, I noted that the html files can be excuted properly,but the php files can not be found and excuted.Text from the server is “No input file specified”.Please tell how to set this kind of alias.
Forgive my pool English.
By the way,the php scritps in /var/ww/html(my root document) can be excuted properly.
2007-10-16 at 2.49 am
Hi,
Thanks! Great post. Unfortunately, I’m seeing a nginx error: 2007/10/15 17:32:17 [error] 5093#0: *3381 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 69.2.2.2, server: http://www.forum.server.com, URL: “/index.php”, upstream: “fastcgi://127.0.0.1:8888″, host: “www.forum.server.com”
I installed the latest php, v2.2.0
Ideas much appreciated,
Larry
2007-10-16 at 3.05 pm
Hello again,
Solved the problem by enabling logging on php (see php.ini) and then sending error out to a file. (See last line of the php start-up script, above.) The error message from php was that FCGI_WEB_SERVER_ADDRS was not set correctly.
Adding FCGI_WEB_SERVER_ADDRS=”127.0.0.1″ to the start-up script solved the problem.
Also note that the php-cgi binary should be used, not the regular php binary.
Regards,
Larry
2007-11-12 at 11.41 am
Поставил себе тоже этот nginx+fastcgi php5+mysql5+eaccelerator
все вроде бы работает, но есть вопрос такой:
у меня 5виртуальных хостов
но пхп работает только если прописать путь аналогичный
fastcgi_param SCRIPT_FILENAME /usr/local/nginx/html$fastcgi_script_name;
где этот путь является путем до одно из хостов. т.е. если написать путь /корень/хост1
все хосты расположены так
корень - хост1
корень - хост2
и т.п.
если задать в параметре путь к корню то пхп пытается обработать тот файл что лежит в нем…
2007-11-13 at 7.31 am
please tell me how to solve the problem,I have waited for the answer for a month.Please.
thanks
There’s a question I have to ask.
My php scripts are in /var/www/my/,so I created a alias for them.
Content:
location /my/
{
alias /vaw/www/my/;
}
After running, I noted that the html files can be excuted properly,but the php files can not be found and excuted.Text from the server is “No input file specified”.Please tell how to set this kind of alias.
Forgive my pool English.
By the way,the php scritps in /var/ww/html(my root document) can be excuted properly.
2007-11-18 at 10.40 am
Кстати да, я до сих пор понять не мог, почему у меня к htc файлам доступ запрещен. А без них верстка под IE6 становится не особо… Кто-нибудь знает, как победить эту проблему? похоже, не у меня одного она.
2007-12-03 at 2.26 pm
your article is nice but does not work. lots of people are experiencing the same error “No input file specified.” - do you have a solution for that?
2007-12-05 at 1.40 pm
solved! make sure that
fastcgi_param SCRIPT_FILENAME
points to the right directory where your script is located. this solved the issue for me!
2007-12-08 at 3.30 am
[...] Nginx With PHP As FastCGI Howto [...]
2007-12-10 at 7.27 am
sewerson - thank you for solve!!!
2008-01-26 at 1.19 pm
[...] Nginx With PHP As FastCGI Howto :: Homo-Adminus Blog by Alexey Kovyrin (tags: nginx php fastcgi performance web httpd deployment) [...]
2008-01-26 at 1.37 pm
[...] Nginx With PHP As FastCGI Howto (with fcgi-start script) [...]
2008-02-02 at 9.50 pm
[...] roughly followed these instructions, but with these [...]
2008-02-18 at 8.49 am
Please respond to this comment by also CCing me. Because you don’t have other kind of subscription.
Thank you for posting this. But I think it is a bit complex.
1. What if I want to run PHP through nginx but without fastcgi (which is way too painful for anything beyond the basic PHP functionality).
2. Also, in my Apache the “DefaultType” is PHP. So I have many programs without a “.php” configuration. In your example config, you tell nginx to serve php files based on the file-extension (.php). Can I tell nginx to serve php files based on “Type” and not the “File Extension”?
Thanks!
2008-02-25 at 9.22 pm
[...] Reconfigure the server. Thinking Nginx, MySQL and FastCGI/PHP. [...]
2008-02-27 at 7.15 am
[...] provided by the web server lighttpd. You can use PHP’s built-in FastCGI manager php-cgi to do the same thing, but it’s not as straight-forward. Plus, if you learn how to use spawn-fcgi, you can easily [...]
2008-03-07 at 7.39 am
Уважаемые подскажите!
Скрипт запуска Fast CGI (который представлен в этой статье) - не полный, у него отсутствует нижняя часть!
Подскажите пожалуйста , где взять этот скрипт полностью?
Большое спасибо
2008-03-08 at 2.53 pm
[...] provided by the web server lighttpd. You can use PHP’s built-in FastCGI manager php-cgi to do the same thing, but it’s not as straight-forward. Plus, if you learn how to use spawn-fcgi, you can easily adapt [...]
2008-03-13 at 12.27 am
Здравствуйте Алексей..
Если не затруднит, подскажите пожалуйста.. имеет-ли смысл играть с директивами буферизации (proxy_buffers, proxy_buffer_size) при проксировании на fastcgi.. ?
Заранее благодарю..
2008-03-28 at 6.14 am
[...] nginx, потому что есть замечательная статья “Настройка Nginx для поддержки PHP при помощи FastCGI“, просто отмечу некоторые детали, упрощающие жизнь. [...]
2008-04-03 at 3.45 am
[...] Alexei Kovyrin, who posted a nice nginx/PHP/FCGI howto. [...]
2008-04-10 at 12.23 pm
Здраствуйте, у меня к вам вопрос, я сделал всё как вы описали в этой статье, но почему то через некоторое время nginx выдает bad gateway, в качестве сревера стоит spawn-fcgi , такое ощущение что cgi сервер коннекты намеренно отбрасывает, перелопатил весь конфиг nginx но проблемы так и не решил
2008-04-10 at 3.15 pm
[...] configuré un script ejecutado cada vez que se arranca el sistema que se crean 7 procesos php en fastcgi a la espera que Nginx les pase algo por hacer. Dado que BlogHogwarts estaba en un VPS, tuve que [...]
2008-05-11 at 5.17 am
hello do you know how to add 1 alias that will affect to all vhost?
2008-05-29 at 6.23 am
If you want to use alias + fastcgi, you could add something like this into config:
location /gallery2-base/ {
alias /usr/share/gallery2/;
index index.php index.html index.htm;
}
location ~ /gallery2-base/.*\.php$ {
if ($fastcgi_script_name ~ /gallery2-base(/.*\.php)$) {
set $valid_fastcgi_script_name $1;
}
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /usr/share/gallery2$valid_fastcgi_script_name;
include /etc/nginx/fastcgi_params;
}
2008-06-05 at 1.17 pm
спасибо за статью.
очень полезно
2008-07-08 at 7.31 am
Помогите передать бэкенду PHP заголовок запроса “If-Modified-Since”, спасибо за статью, но мало чем помогло в моем случае.
2008-07-21 at 9.38 am
[...] host: "**************" ho compilato php con il supporto fastcgi poi ho seguito questa guida facendo partire lo script usando questo comando: [...]
2008-07-28 at 12.08 pm
Здравстуйте. У ngnix я заметил такой недостаток как то, что он делает буферизацию пост запросов, а в моих сайтах часто используюся аплоады прогресс бары и из - за этой буферизации скрипты полчуют в tmp уже полность загруженный файл, то есть поргресс бар стоит на нуле а птом сразу 100%
Есть ли у ngnix какая - нид возможность отключить будеризацию пост запросос и сразу направлять их php
2008-08-03 at 7.51 am
Искренне рекомендую пользоваться swfupload
2008-08-10 at 10.02 pm
этот вариант только если в проекте допускаются флэшки. ЩАс пока у нас сделали так что к апачу можно пробиться вне ngnix по нестандартному порту и через него работаем с нашим аплоадером.
2008-08-10 at 10.09 pm
У нас обычно nginx проксирует запросы к нескольким монгрелам, поэтому отдельный порт не укажешь.