Nginx php-cgi

Материал из wiki.lissyara.su
Перейти к: навигация, поиск
Что нужно:
Альтернатива Apache + PHP.

Установка nginx:

cd/usr/ports/www/nginx
make install clean

Оставляем всё по умолчанию/пониманию:
[X] HTTP_MODULE
[X] HTTP_REWRITE_MODULE
[X] HTTP_STATUS_MODULE
[X] WWW

Устанавливаем PHP:

cd /usr/ports/lang/php5
make install clean

Оставляем всё по умолчанию/пониманию:
[X] CLI	Build CLI version                                
[X] CGI	Build CGI version                                               
[X] SUHOSIN	Enable Suhosin protection system (not for jails)
[X] REDIRECT	Enable force-cgi-redirect support (CGI only)     
[X] DISCARD	Enable discard-path support (CGI only)           
[X] FASTCGI	Enable fastcgi support (CGI only)                
[X] PATHINFO	Enable path-info-check support (CGI only)  

Устанавливаем PHP-extensions:

cd /usr/ports/lang/php5-extensions
make install clean

По мере необходимости отмечаем необходимые модули, postfixadmin и roundcube требуют:
[X] DOM	DOM support
[X] GD		GD library support
[X] ICONV	iconv support
[X] IMAP	IMAP support
[X] MBSTRING	multibyte string support
[X] MYSQL	MySQL database support
[X] SESSION	session support
[X] SIMPLEXML	simplexml support
[X] SPL	Standard PHP Library

Создаём скрипт запуска fcgi-сервера:
/usr/local/etc/rc.d/php-cgi

#!/bin/sh
#
# PROVIDE: php_fastcgi
# REQUIRE: DAEMON
# BEFORE:  LOGIN
# KEYWORD: shutdown

. /etc/rc.subr

name="php_fastcgi"
rcvar=`set_rcvar`

load_rc_config $name

: ${php_fastcgi_enable="NO"}
: ${php_fastcgi_user="www"}
: ${php_fastcgi_bindaddr="127.0.0.1"}
: ${php_fastcgi_bindport="9000"}
: ${php_fastcgi_children="5"}
: ${php_fastcgi_max_requests="1000"}
: ${php_fastcgi_allowed_env=""}

export PHP_FCGI_CHILDREN=${php_fastcgi_children};
export PHP_FCGI_MAX_REQUESTS=${php_fastcgi_max_requests};

command="/usr/local/bin/php-cgi";
command_args="-q -b ${php_fastcgi_bindaddr}:${php_fastcgi_bindport} &";
pidfile="/var/run/${name}.pid";

_allowed_env="ORACLE_HOME PATH USER PHP_FCGI_CHILDREN PHP_FCGI_MAX_REQUESTS FCGI_WEB_SERVER_ADDRS";
_allowed_env="${_allowed_env} ${php_fastcgi_allowed_env}";

start_precmd=start_precmd;
start_postcmd="sleep 1;ps -U ${php_fastcgi_user} -o 'pid,command'|grep ${command}|head -1|\
		awk '{print \$1}' > ${pidfile}";
stop_postcmd=stop_postcmd;

start_precmd()
{
   export USER=${php_fastcgi_user};
   E=
   for i in ${_allowed_env}; do
       eval _val="\$$i";
       if [ "${_val}_x" != "_x" ]; then
           eval _add="$i=$_val";
           E="${E} ${_add}";
       fi
   done
   command="env - ${E} ${command}";
}

stop_postcmd()
{
    rm -f $pidfile
}

load_rc_config $name;

run_rc_command "$1";

Примерно до такого содержания правим конфигурационный файл (nginx.conf):

/usr/local/etc/nginx/nginx.conf

user  www;
worker_processes  3;

pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile       on;
    tcp_nopush     on;
    tcp_nodelay    on;
    keepalive_timeout  65;
    server_names_hash_max_size 2048;
    server_names_hash_bucket_size 128;
    server {
        listen       80;
        server_name  ИМЯ_СЕРВЕРА или IP_Адрес;
        charset utf8;
        client_max_body_size    25m;  # 25Мбайт для body (К примеру, вложение в письме)
        location / {
            root   /usr/local/www;
            index  index.html index.php;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/local/www/nginx;
        }
        location ~ \.php$ {
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  /usr/local/www$fastcgi_script_name;
            include        fastcgi_params;
        }

        location /nginx-status {
        # Это для просмотра статистики по http://ИМЯ_СЕРВЕРА или IP_Адрес/nginx-status
        stub_status     on;
        access_log      off;
        allow   192.168.2.0/24;
        deny all;

        }
    }
}

Прописываем всё в rc.conf:

nginx_enable="YES"
php_fastcgi_enable="YES"
php_fastcgi_user="www"
php_fastcgi_bindaddr="127.0.0.1"
php_fastcgi_bindport="9000"
php_fastcgi_children="5"
php_fastcgi_max_requests="1000"
php_fastcgi_allowed_env=""

Всё, теперь запускаем php-cgi,nginx и проверяем работу. Если вносите изменения в php.ini перезапускать нужно php-cgi.


Может пригодится:
# /usr/local/bin/php-cgi --help

Usage: php-cgi [-q] [-h] [-s] [-v] [-i] [-f <file>]
       php-cgi <file> [args...]
 -a               Run interactively
 -b <address:port>|<port> Bind Path for external FASTCGI Server mode
 -C               Do not chdir to the script's directory
 -c <path>|<file> Look for php.ini file in this directory
 -n               No php.ini file will be used
 -d foo[=bar]     Define INI entry foo with value 'bar'
 -e               Generate extended information for debugger/profiler
 -f <file>        Parse <file>.  Implies `-q'
 -h               This help
 -i               PHP information
 -l               Syntax check only (lint)
 -m               Show compiled in modules
 -q               Quiet-mode.  Suppress HTTP Header output.
 -s               Display colour syntax highlighted source.
 -v               Version number
 -w               Display source with stripped comments and whitespace.
 -z <file>        Load Zend extension <file>.
 -T <count>       Measure execution time of script repeated <count> times.

Посмотреть версию php можно так:
# /usr/local/bin/php-cgi -v

PHP 5.2.6 with Suhosin-Patch 0.9.6.2 (cgi-fcgi) (built: Nov 19 2008 14:14:48)
Copyright (c) 1997-2008 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies

Список модулей:
# /usr/local/bin/php-cgi -m

[PHP Modules]
cgi-fcgi
date
dom
gd
iconv
imap
libxml
mbstring
mysql
pcre
Reflection
session
SimpleXML
SPL
standard

[Zend Modules]

Источники:

http://www.lissyara.su/?id=1532 + комментарий nikll

http://sysoev.ru/nginx/