Nginx With PHP As FastCGI Howto

Posted by Alexey Kovyrin under Networks · русский

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.

Since this article has been published long time ago, there is MUCH better option to manage PHP FastCGI processes than the one I described below. Please check out php-fpm project from Andrei Nigmatulin which IMHO is the best possible way to manage PHP processes.

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:

1
2
3
4
5
6
7
# ./configure --prefix=/opt/php --enable-fastcgi
...
# 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/bin/bash

## 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):

1
2
3
4
5
6
7
8
9
10
11
12
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:8888
#
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.


Related posts:

  1. Typical Configurations Overview For Nginx HTTP(S) Reverse Proxy/Web Server
  2. Nginx – Small, But Very Powerful and Efficient Web Server
  3. Monitoring nginx Server Statistics With rrdtool
  4. High-Performance Ruby On Rails Setups Test: mongrel vs lighttpd vs nginx
  5. Using Nginx As Reverse-Proxy Server On High-Loaded Sites

76 Responses to this entry

Erick says:

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!

e_nagual says:

Уважаемые подскажите!

Скрипт запуска Fast CGI (который представлен в этой статье) – не полный, у него отсутствует нижняя часть!

Подскажите пожалуйста , где взять этот скрипт полностью?

Большое спасибо

garrotte says:

Здравствуйте Алексей..
Если не затруднит, подскажите пожалуйста.. имеет-ли смысл играть с директивами буферизации (proxy_buffers, proxy_buffer_size) при проксировании на fastcgi.. ?
Заранее благодарю..

Anton says:

Здраствуйте, у меня к вам вопрос, я сделал всё как вы описали в этой статье, но почему то через некоторое время nginx выдает bad gateway, в качестве сревера стоит spawn-fcgi , такое ощущение что cgi сервер коннекты намеренно отбрасывает, перелопатил весь конфиг nginx но проблемы так и не решил

Denis says:

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;
}

йожег says:

Помогите передать бэкенду PHP заголовок запроса “If-Modified-Since”, спасибо за статью, но мало чем помогло в моем случае.

_kT says:

Здравстуйте. У ngnix я заметил такой недостаток как то, что он делает буферизацию пост запросов, а в моих сайтах часто используюся аплоады прогресс бары и из – за этой буферизации скрипты полчуют в tmp уже полность загруженный файл, то есть поргресс бар стоит на нуле а птом сразу 100%

Есть ли у ngnix какая – нид возможность отключить будеризацию пост запросос и сразу направлять их php

_kT says:

этот вариант только если в проекте допускаются флэшки. ЩАс пока у нас сделали так что к апачу можно пробиться вне ngnix по нестандартному порту и через него работаем с нашим аплоадером.

Макс Лапшин says:

У нас обычно nginx проксирует запросы к нескольким монгрелам, поэтому отдельный порт не укажешь.

Vas says:

nginx 0.7.16, настроил rewrite – упорно отдаёт http://server/index.php?Login как octet-stream и нипочём не хочет прогнать его сквозь php

Само php работает…

Даже добавление
location ~ \(.*\) {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME трампампам$fastcgi_script_name;
include fastcgi_params;
}
не помогает :(

Может nginx принципиально прогоняет через php только один раз?