Nginx (Русский)
Contents |
Введение
nginx [engine x], написанный Игорем Сысоевым в 2004-ом году — это свободный высокопроизводительный HTTP-сервер и почтовый прокси-сервер, имеющий открытый код. Согласно Обзору Web-серверов от Netcraft за июнь 2009 nginx используется на 3.37% доменов во всём мире, в то время как lighttpd используется на 1.8%. Nginx сейчас известен за его стабильность, богатый набор функций, простое конфигурирование («в духе» Arch), и низкое потребление ресурсов.
Установка
Пакет nginx сейчас доступен в [community] репозитории, последняя стабильная версия nginx-1.0.0:
# pacman -S nginx
Или вы можете собрать и установить последнюю development версию через ABS.
Запуск демона
Убедитесь, что в /etc/rc.d/nginx есть следующая строка:
PID="/var/run/nginx.pid"
После чего выполните:
# rc.d start nginx
Для запуска демона, теперь nginx запущен. По умолчанию корень сайта(т.е. страница отдаваемая по http://127.0.0.1) находится в /srv/http/nginx/
(Пакет Nginx'a не устанавливает стандартный index.html, вы должны создать его сами, если захотите.)
После создания страницы /srv/http/nginx/index.html вы можете использовать http://127.0.0.1 для проверки работоспособности Nginx.
Для загрузки демона nginx с запуском системы нужно добавить "nginx" в DAEMONS в конфигурационном файле /etc/rc.conf:
DAEMONS=(syslog-ng hal .. nginx)
Настройка
Вы можете конфигурировать nginx правкой конфигов в /etc/nginx/conf. (/etc/nginx/nginx.conf является основным конфигурационным файлом).
Более подробную информацию по настройке вы можете прочитать на sysoev.ru/nginx/docs/ и Nginx Configuration Examples.
Поддержка PHP/Python в Nginx
FastCGI используется в Nginx для работы с внешними инструментами и серверами, т.е. PHP и Python. Вы не можете использовать PHP и Python без запущенного FastCGI сервера.
PHP и Python могут быть запущены как FastCGI и способны обрабатывать FastCGI запросы от Nginx.
FastCGI как правило дает более высокую производительность чем например Apache, где PHP загружается каждый раз, с FastCGI скрипт просто обрабатывается PHP демоном и результат работы скрипта возвращается Nginx'у.
Шаг 1: Запуск FastCGI сервера
Есть 2 варианта настройки FastCGI сервера.
Новый метод: PHP-Fpm(начиная с PHP 5.3.3)
PHP сейчас включает FastCGI сервер, который устраняет ряд проблем, мешающих использовать FastCGI на высоконагруженных системах.
Для запуска введите: (С правами пользователя root, `su -`)
# pacman -S php-fpm # rc.d start php-fpm
Старый метод (встроенный в PHP сервер)
Заключается в запуске встроенного в PHP FastCGI сервера. Этот метод не требует использования сторонних инструментов.
php пакет в Archlinux в [extra] репозитории собран с поддержкой FastCGI.
Для примера:
# pacman -S php php-cgi $ php-cgi -b 127.0.0.1:9000 &
Запустит FastCGI сервер на 9000 порту.
Этот скрипт используется для запуска FastCGI сервера в /etc/rc.conf при загрузке системы. Сохраните его в и добавьте "fastcgi" в секцию DAEMONS в /etc/rc.conf
#!/bin/bash
. /etc/rc.conf
. /etc/rc.d/functions
case "$1" in
start)
stat_busy 'Starting Fastcgi Server'
if /usr/bin/php-cgi -b 127.0.0.1:9000 &
then
add_daemon fastcgi
stat_done
else
stat_fail fi
fi
;;
stop)
stat_busy 'Stopping Fastcgi Server'
[ -e /var/run/daemons/fastcgi ] && kill $(pidof php-cgi) &> /dev/null;
if [ $? -gt 0 ]; then
stat_fail
else
rm_daemon fastcgi
stat_done
fi
;;
restart)
$0 stop
$0 start
;;
*)
echo "Usage: $0 {start|stop|restart}"
esac
Method two (Third-party-wrapper)
This can be more comfortable than the first method because of increased flexibility.
There are currently three options for deploying PHP on NginX:
- fcgi
- Includes cgi-fcgi
- lighttpd
- Includes spawn-fcgi
- PHP-FPM (Recommended: see above)
To spawn a process, issue one of the following commands (matching the package you installed):
# cgi-fcgi -start -connect localhost:9000 /usr/bin/php-cgi
# spawn-fcgi -a 127.0.0.1 -p 9000 -C 9 -f /usr/bin/php-cgi
# php --fpm -b 127.0.0.1:
Шаг 2: Правка конфига /etc/nginx/conf/nginx.conf
- 1: Добавьте index.php после index.html в директиву index:
location / {
root html;
index index.html index.htm index.php;
}
- 2: Раскомментируйте эти опции для включения поддержки PHP в Nginx:
location ~ \.php$ {
try_files $uri =404;
root html;
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
Шаг 3: перезапуск Nginx
Если Nginx был запущен выполните:
# rc.d restart nginx
Отредактируйте /srv/http/nginx/index.php,
<?php phpinfo(); ?>
Зайдите на: http://localhost/index.php и проверьте нормально ли NginX работает с PHP.
Ruby (Rack-based and Rails)
The Ruby on Rails wiki has tutorials on configuring Ruby for Nginx. It is not recommended to use FastCGI to make Nginx work with Ruby anymore, although very well possible. Nginx and Passenger are a great toolkit, and this setup is extremely easy to achieve on Arch Linux. It should be noted, however, that there are other alternatives, including Mongrel, Thin and Unicorn.
Setting up Nginx and Passenger
Install the Nginx Passenger package from AUR, and you are ready to go.
For further information on setting up Nginx with Ruby, read the Nginx part of this tutorial.
Решение возможных проблем
Доступ с локальных IP перенаправляется на localhost
Решение взято с forum.
Отредактируйте /etc/nginx/nginx.conf и добавьте ниже "server_name localhost" строку:
server_name_in_redirect off;
Default behavior is that nginx redirects any requests to the value given as server_name in the config.
Error: 403 (Permission error)
This is most likely a permission error. Are you sure whatever user configured in the Nginx configuration is able to read the correct files?
If the files are located within a home directory, (e.g. /home/arch/public/webapp) and you are sure the user running Nginx has the right permissions (you can temporarily chmod all the files to 777 in order to determent this), /home/arch might be chmod 750, simply chmod it to 751, and it should work.
This is because the FastCGI server has not been started.
Error: No input file specified
Most Likely you don't have the SCRIPT_FILENAME containing the full path to you scripts. If the configuration of nginx (fastcgi_param SCRIPT_FILENAME) is all right, this kind of error means php fail to load the requestd script. Usually it's simply an permission issue, you can just run php-cgi as root
# spawn-fcgi -a 127.0.0.1 -p 9000 -f /usr/bin/php-cgi
or you should create some group and user to start the php-cgi. For instance :
# groupadd www # useradd -g www www # chmod +w /srv/www/nginx/html # chown -R www:www /srv/www/nginx/html # spawn-fcgi -a 127.0.0.1 -p 9000 -u www -g www -f /usr/bin/php-cgi
Another occasion is that, wrong "root" argument in the "location ~ \.php$" section in nginx.conf, make sure the "root" points to the same directory as it in "location /" in the same server. Or you may just set root as global, don't define it in any location section.
Also keep in mind that your php script path was defined as /srv/www/nginx/html by default using the variable "open_basedir" in /etc/php/php.ini, you can change them if you need.
Рекомендации
Во избежания "несчастных случаев" настоятельно рекомендую создать группу и пользователя c именем "www" и права на запись /srv/http/nginx/ этому пользователю.