Nginx 1.4.x на Unix системах

В цьому розділі описано встановлення та конфігурування PHP з PHP-FPM для HTTP-сервера Nginx 1.4.x.

Якщо ви збирали Nginx з сирців, то всі бінарні та конфігураційні файли зберігаються в /usr/local/nginx. В іншому випадку, можете описати ваш процес встановлення на » Nginx Wiki.

Тут буде описуватись лише основне конфігурування сервера Nginx, щоб він міг обробляти PHP застосунки на 80-му порту. В іншому випадку рекомендуємо прочитати документацію Nginx для PHP-FPM.

Нижче на цій сторінці будуть зустрічатись маски 'x' на місці номера версії. Це зроблено з узагальнюючою метою, оскільки викладені тут рекомендації підійдуть для ряду версій. Дані маски потрібно замінити на відповідний номер вашої версії Nginx.

  1. Рекомендуємо відвідати Nginx Wiki та прочитати » сторінку встановлення, щоб правильно встановити Nginx.

  2. Скачайте та розпакуйте сирці PHP:

    tar zxf php-x.x.x
    
  3. Зараз ви можете компонувати збірку PHP, наприклад, визначивши які розширення будуть включені. Щоб проглянути список доступних параметрів, запустіть ./configure --help. В нашому прикладі ми зробимо просту конфігурацію з підтримкою PHP-FPM та MySQL.

    cd ../php-x.x.x
    ./configure --enable-fpm --with-mysql
    make
    sudo make install
    
  4. Тепер скопіюємо конфігураційні файли в їхнє коректне місцерозташування

    cp php.ini-development /usr/local/php/php.ini
    cp /usr/local/etc/php-fpm.conf.default /usr/local/etc/php-fpm.conf
    cp sapi/fpm/php-fpm /usr/local/bin
    
  5. Важливо, щоб ми убезпечили Nginx від проходження запитів до PHP-FPM, коли файла не існує. Таким чином ми запобігаємо від довільної ін'єкції скрипта.

    Це можна зробити встановивши директиву cgi.fix_pathinfo в 0 всередині файла php.ini.

    Відкриваємо файл php.ini:

    vim /usr/local/php/php.ini
    

    Знаходимо директиву cgi.fix_pathinfo= та змінюємо її так:

    cgi.fix_pathinfo=0
    
  6. В файлі php-fpm.conf потрібно зазначити, що php-fpm повинен запускатись під користувачем www-data та в групі www-data перед тим, як будемо запускати сервіс:

    vim /usr/local/etc/php-fpm.conf
    

    Знайдіть та змініть наступне:

    ; Користувач чи група Unix процесів
    ; Замітка: визначити користувача (user) потрібно обов'язково. Якщо групу не
    ; встановлено, буде використовуватись початкова група.
    user = www-data
    group = www-data
    

    Тепер можна запускати сервіс php-fpm:

    /usr/local/bin/php-fpm
    

    На цьому налаштування php-fpm припиняється, але якщо ви зацікавлені в більш детальному налаштуванні, то рекомендуємо читати відповідну документацію.

  7. Тепер Nginx потрібно налаштувати для обробки PHP застосунків:

    vim /usr/local/nginx/conf/nginx.conf
    

    Змінюємо блок "location", щоб додати до індексних файлів розширення .php:

    location / {
        root   html;
        index  index.php index.html index.htm;
    }

    На наступному кроці ми говоримо, щоб всі файли .php передавались до PHP-FPM, нижче від закоментованого блоку location, додайте таке:

    location ~* \.php$ {
        fastcgi_index   index.php;
        fastcgi_pass    127.0.0.1:9000;
        include         fastcgi_params;
        fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
        fastcgi_param   SCRIPT_NAME        $fastcgi_script_name;
    }

    Перезапускаємо Nginx.

    sudo /usr/local/nginx/sbin/nginx -s stop
    sudo /usr/local/nginx/sbin/nginx
    
  8. Створюємо тестовий файл

    rm /usr/local/nginx/html/index.html
    echo "<?php phpinfo(); ?>" >> /usr/local/nginx/html/index.php
    

    Перейдіть за адресою http://localhost. Тепер phpinfo() вже повинно виводитись.

Дотримуючись кроків, описаних вище, ви матимете робочий веб-сервер Nginx, який підтримує PHP як модуль SAPI. Звичайно є набагато більше параметрів конфігурації доступних для Nginx та PHP. Більше інформації можна отримати ввівши в консолі ./configure --help в їх кореневих каталогах.

add a note add a note

User Contributed Notes 9 notes

up
30
Lenny
8 years ago
Building from source is not easy if something is a bit different, and I had a hard time with some directory and configuration options. I was floundering around the web until I found this site that translated from Chinese. No one else had the solution.  I couldn't get php fpm to start until I changed the directory (Item 2.ERROR: Unable to globalize). I had other issues listed but I was able to solve them. Please don't delete this, it is very useful info.

The original site  (it is in Chinese, not my site, but I want to give credit):

(there is some more there, you can goto the site)

blog.dream1987.top/?paged=2

Installation problems:

1. configure: error:. Xml2-config not found Please check your libxml2 installation.

solution:

apt-get install libxml2-dev



2.Warning: Declaration of PEAR_Installer :: download () should be compatible with & PEAR_Downloader :: download ($ params) in phar: ///root/php-7.0.0alpha1/pear/install-pear-nozlib.phar/PEAR /Installer.php on line 43

Warning: Declaration of PEAR_PackageFile_Parser_v2 :: parse () should be compatible with PEAR_XMLParser :: parse ($ data) in phar: ///root/php-7.0.0alpha1/pear/install-pear-nozlib.phar/PEAR/PackageFile/ Parser / v2.php on line 113
[PEAR] Archive_Tar - already installed: 1.3.13
[PEAR] Console_Getopt - already installed: 1.3.1
[PEAR] Structures_Graph- already installed: 1.0.4

Warning: Declaration of PEAR_Task_Replace :: init () should be compatible with PEAR_Task_Common :: init ($ xml, $ fileAttributes, $ lastVersion) in phar: ///root/php-7.0.0alpha1/pear/install-pear-nozlib. phar / PEAR / Task / Replace.php on line 31
[PEAR] XML_Util - already installed: 1.2.3

Warning: Declaration of PEAR_Task_Windowseol :: init () should be compatible with PEAR_Task_Common :: init ($ xml, $ fileAttributes, $ lastVersion) in phar: ///root/php-7.0.0alpha1/pear/install-pear-nozlib. phar / PEAR / Task / Windowseol.php on line 76

Warning: Declaration of PEAR_Task_Unixeol :: init () should be compatible with PEAR_Task_Common :: init ($ xml, $ fileAttributes, $ lastVersion) in phar: ///root/php-7.0.0alpha1/pear/install-pear-nozlib. phar / PEAR / Task / Unixeol.php on line 76
[PEAR] PEAR - already installed: 1.9.5

solution:

Workaround not found (http://pear.php.net/bugs/bug.php?id=20554)

3. Start php-fpm

1.ERROR: failed to open configuration file '/usr/local/etc/php-fpm.conf': No such file or directory (2)
ERROR: failed to load configuration file '/usr/local/etc/php-fpm.conf'
ERROR: FPM initialization failed

solution:

Php-fpm.conf copy files from the source file to that location.

cp /root/php-7.0.0alpha1/sapi/fpm/php-fpm.conf /usr/local/etc/php-fpm.conf

2.ERROR: Unable to globalize '/usr/local/NONE/etc/php-fpm.d/*.conf' (ret = 2) from /usr/local/etc/php-fpm.conf at line 125.
ERROR: failed to load configuration file '/usr/local/etc/php-fpm.conf'
ERROR: FPM initialization failed

solution:

Edit /usr/local/etc/php-fpm.conf document introduced * .conf part, change to the correct path include = / usr / local / etc / php-fpm.d / *. Conf

If there is no /usr/local/etc/php-fpm.d directory, create the directory.

3.WARNING: Nothing matches the include pattern '/usr/local/etc/php-fpm.d/*.conf' from /usr/local/etc/php-fpm.conf at line 125.
ERROR:. No pool defined at least one pool section must be specified in config file
ERROR: failed to post process the configuration
ERROR: FPM initialization failed

solution:

cp www.conf.default www.conf

4.ERROR: [pool www] can not get gid for group 'nobody'
ERROR: FPM initialization failed

solution:

Www.conf open files, user and group users into nginx default settings, usually the default is www-data.
up
2
1097625354 at qq dot com
5 years ago
cp php/php.ini-development        php/lib/php.ini
cp php/etc/php-fpm.conf.default       php/etc/php-fpm.conf
cp php/etc/php-fpm.d/www.conf.default     php/etc/php-fpm.d/www.conf
up
1
Leon Nguyen vnlab
2 years ago
To maximize the server performance with highest speed, with fewest resources, i have decided to compile PHP 8 manually from minimal Linux/Unix-based OS (my Linux distro is rpm-based packages)

My system has successfully powered up by PHP 8.0.9 - with Opcache/JIT enabled & other several PHP extension module. Here is several experience that may save you several hours of research.

1. Before step (3) - Configure and build PHP - to ensure that no errors occurs, you can refer to my prerequisites library.

sudo dnf install \
gcc gcc-c++ make cmake autoconfig \
zlib zlib-devel pcre pcre-devel \
libxml2-devel libxslt-devel \
bzip2-devel curl-devel libzip-devel\
sqlite-devel \
systemd-devel \
openssl-devel \
libffi-devel \
libpng libpng-devel libwebp libwebp-devel libjpeg libjpeg-devel libXpm libXpm-devel \
freetype-devel \
gmp-devel \
libldb-devel \
libc-client libc-client-devel \
openldap openldap-devel \
oniguruma oniguruma-devel \
net-snmp-devel readline-devel unixODBC-devel \
uw-imap uw-imap-devel uw-imap-static uw-imap-utils \
libicu-devel \
enchant2 enchant2-devel \
gd gd-devel \
libsodium libsodium-devel \
libtidy libtidy-devel

You may not receive error when issuing ./configure, make && make install. Even when you manually build your PHP extension package later.

2. At step 5 - before modifying php.ini - you may double-check whether the current PHP is reading which php.ini file by this command

php -ini | grep php.ini
# My result. It is different from tutorial.
Configuration File (php.ini) Path => /usr/local/lib
Loaded Configuration File => /usr/local/lib/php.ini
up
0
uanaoeng at outlook dot com
5 years ago
When I run the following command to start the php-fpm:
/usr/local/bin/php-fpm

I got the following error information:
Unable to globalize '/usr/local/NONE/etc/php-fpm.d/*.conf' (ret=2) from /usr/local/etc/php-fpm.conf at line 143.

To fix this error, do:
change the string "include=NONE/etc/php-fpm.d/*.conf" to "include=etc/php-fpm.d/*.conf" in the file "/usr/local/etc/php-fpm.conf" with text editor.

After that, I try to start the php-fpm again and got error information again:
Nothing matches the include pattern '/usr/local/etc/php-fpm.d/*.conf' from /usr/local/etc/php-fpm.conf at line 143.

To fix this error, do:
cp /usr/local/etc/php-fpm.d/www.conf.default /usr/local/etc/php-fpm.d/www.conf
up
0
sp at rysmax dot com
6 years ago
Translate errors:

Теперь перейдите в http://localhsot
Теперь перейдите в http://localhost

В этом разделе описивыется
В этом разделе описывается

запрещаем Nginx от отправлять
запрещаем Nginx отправлять
up
-1
610010559 at qq dot com
4 years ago
in linux system, if you want to add php-fpm service to system service;  it is easy to do that, because php offer the relate shell script:

after make and make install;enter the source code package sapi/fpm/init.d.php-fpm ; type the code in the linux system. 
cp sapi/fpm/init.d.php-fpm  /etc/init.d/php-fpm

then you can use "php-fpm {start|stop|force-quit|restart|reload|status|configtest} "  command  to control your php-fpm program more convenient .
up
0
nguyentienlong88 at gmail dot com
8 years ago
at step 3, after command "sudo make install"
if there is problem with pear.php.net (https). Need to change this line (from https to http) in Makefile
PEAR_INSTALLER_URL = http://pear.php.net/install-pear-nozlib.phar
up
-1
Akash Kumar Sharma
8 years ago
If you get "File not found" error then add "root ROOT_DIR_LOCATION" directive to PHP location block i.e. "location ~* \.php$ { }" , where ROOT_DIR_LOCATION is root directory like "/usr/share/nginx/html" .
up
-2
nguyentienlong88 at gmail dot com
8 years ago
at step 3, if there is no configure script yet, you need to rebuiding configure script using this command:
  
./buildconf --force
To Top