Web-server = Nginx + PHP, установка nginx

Материал из ИНФОвики
Перейти к: навигация, поиск

Web-server = Nginx + PHP, установка nginx

Скачать последний стабильный выпуск nginx можно с официального сайта. Я создал копию последней стабильной версии на момент написания статьи: nginx-1.0.14.tar.gz.

Скачиваем nginx:

cd /usr/local/src/arc
wget -c http://download.boyandin.info/linux/web/src/nginx-1.0.14.tar.gz

Распаковываем и запускаем конфигуратор:

cd /usr/local/src/install
tar xzf /usr/local/src/arc/nginx-1.0.14.tar.gz
cd nginx-1.0.14
./configure \
 --prefix=/usr/local/nginx-1.0.14 \
 --user=apache \
 --group=apache \
 --with-rtsig_module \
 --with-http_ssl_module \
 --with-http_realip_module \
 --with-http_addition_module \
 --with-http_xslt_module \
 --with-http_image_filter_module \
 --with-http_geoip_module \
 --with-http_sub_module \
 --with-http_dav_module \
 --with-http_flv_module \
 --with-http_gzip_static_module \
 --with-http_random_index_module \
 --with-http_secure_link_module \
 --with-http_degradation_module \
 --with-http_stub_status_module \
 --with-pcre 1> configure.out 2> configure.err

Собираем и устанавливаем:

make 1> make.out 2> make.err
make install 1> make-install.out 2> make-install.err

Создаём каталог для хранения журналов

mkdir /var/log/nginx
chown apache:apache /var/log/nginx

Создаём файл конфигурации. В примере ниже указаны настройки, пригодные по умолчанию, например, для Wordpress

user              apache apache;
worker_processes  2;
timer_resolution  100ms;
error_log         /var/log/nginx/error.log;
pid               /var/run/nginx.pid;

events {
    worker_connections  128;
    use epoll;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    charset                      utf-8;
    client_max_body_size         2m;
    client_header_buffer_size    2k;
    large_client_header_buffers  4 4k;

#
# Тайм-ауты
#
    client_body_timeout   25;
    client_header_timeout 5;
    keepalive_timeout     25 5;
    send_timeout          25;

#        
# Разнообразные настройки
#
    ignore_invalid_headers   on;
    recursive_error_pages    on;
    sendfile                 on;
    server_name_in_redirect off;
    server_tokens           off;

#
# Настройки TCP
#
    tcp_nodelay on;
    tcp_nopush  on;
#
# Кэширование открытых файлов
#
    open_file_cache          max=1000 inactive=300s;
    open_file_cache_valid    360s;
    open_file_cache_min_uses 2;
    open_file_cache_errors   off;

#    
# Сжатие данных
#
    gzip              on;
    gzip_static       on;
    gzip_buffers      16 8k;
    gzip_comp_level   9;
    gzip_http_version 1.0;
    gzip_min_length   0;
    gzip_types        text/plain text/css image/x-icon image/bmp;
    gzip_vary         on;

#
# Формат записи в журнале - установим так, чтобы его понимали awstat и прочие
# 
    log_format  main  '$remote_addr - $remote_user [$time_local] $request '
                      '"$status" $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" "$http_host"';

    # access_log  /var/log/nginx/access.log  main;

    # Настройки, чтобы ограничить поисковых и пр. ботов
    limit_req_zone $binary_remote_addr zone=one:5m rate=2r/s;

    #
    # Настройки сайта (сайтов в файле настроек может быть произвольно много)
    #
    server {
        listen       *:80;
        server_name  localhost; # укажите здесь все доменные имена сайта через пробел
        access_log  /var/log/nginx/localhost.access.log  main;
        root        /your/web/root; # укажите, где расположен корневой каталог сайта

        # Не записывать обращение к статическим файлам
        location ~* \.(jpg|jpeg|gif|css|png|js|ico)$ {
            access_log        off;
        }
        # Обработчик адресов - годится для WordPress 
        location / {
            try_files $uri $uri/ /index.php;
            index  index.php index.html;
        }

        # Если страница не найдена, вернуть статическую страницу ошибки 
        error_page  404              /404.html;
        location = /404.html {
            root   /usr/local/nginx/html;
        }

        # Тоже для случая, когда сервер сообщает об ошибке /50x.html
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/local/nginx/html;
        }

        # Обрабатываем PHP через FastCGI
        location ~ \.php$ {
            try_files $fastcgi_script_name =404;
            limit_req zone=one burst=3 nodelay;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }

        # Запретим доступ к файлам, имена которых начинаются на .ht
        location ~ /\.ht {
            deny  all;
        }
    }
}

Теперь создадим файл для автоматического запуска nginx, /etc/init.d/nginx:

#!/bin/sh
#
# nginx - this script starts and stops the nginx daemin
#
# chkconfig:   - 85 15 
# description:  Nginx is an HTTP(S) server, HTTP(S) reverse \
#               proxy and IMAP/POP3 proxy server
# processname: nginx
# config:      /url/local/nginx/conf/nginx.conf
# config:      /etc/sysconfig/nginx
# pidfile:     /var/run/nginx.pid

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0

nginx="/usr/local/nginx/sbin/nginx"
prog=$(basename $nginx)

NGINX_CONF_FILE="/usr/local/nginx/conf/nginx.conf"

[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx

lockfile=/var/lock/subsys/nginx

start() {
    [ -x $nginx ] || exit 5
    [ -f $NGINX_CONF_FILE ] || exit 6
    echo -n $"Starting $prog: "
    daemon $nginx -c $NGINX_CONF_FILE
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}

stop() {
    echo -n $"Stopping $prog: "
    killproc $prog -QUIT
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}

restart() {
    configtest || return $?
    stop
    start
}

reload() {
    configtest || return $?
    echo -n $"Reloading $prog: "
    killproc $nginx -HUP
    RETVAL=$?
    echo
}

force_reload() {
    restart
}

configtest() {
    $nginx -t -c $NGINX_CONF_FILE
}

rh_status() {
    status $prog
}

rh_status_q() {
    rh_status >/dev/null 2>&1
}

case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart|configtest)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
	    ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
        exit 2
esac

Добавим скрипт для автоматической загрузки:

chkconfig --add nginx
chkconfig nginx on

Запускаем nginx:

service nginx start

Вернуться на статью про установку Web-среды: Web-server = Nginx + PHP.

комментарии поддерживаются Disqus