Данная документация описывает процесс установки и настройки PHP с
PHP-FPM для Nginx 1.4.x HTTP сервера.
Данное руководство подразумевает, что вы собрали Nginx из исходников, следовательно,
все бинарные файлы и файлы конфигурации располагаются в
/usr/local/nginx
. Если нет, и вы получили Nginx другим способом, тогда,
пожалуйста, обратитесь к » Nginx Wiki, чтобы перевести
данное руководство для вашей установки.
Данное руководство охватывает азы настройки Nginx сервера, для обработки PHP приложений
и отображения их на порту 80. Рекомендуется изучить документацию Nginx и PHP-FPM, если
вы хотите оптимизировать вашу установку за рамками данной документации.
Пожалуйста, обратите внимание, что во всей данной документации номера версий были
заменены на ‘x’, чтобы данная документация оставалась корректной в будущем.
Пожалуйста, замените ‘x’ на необходимый вам номер версии.
-
Рекомендуется посетить
» страницу установки на Nginx Wiki,
для информации о получении и установке Nginx. -
Получение и распаковка исходники PHP:
-
Настройка и сборка PHP. В этом разделе описывается настройка и сборка PHP из
исходных кодов.
Запустите ./configure —help для получения списка доступных опций. В нашем примере
мы сделаем простые настройки с PHP-FPM и поддержкой MySQLi.cd ../php-x.x.x ./configure --enable-fpm --with-mysqli make sudo make install
-
Перемещение файлов настройки в нужные директории
cp php.ini-development /usr/local/php/php.ini cp /usr/local/etc/php-fpm.d/www.conf.default /usr/local/etc/php-fpm.d/www.conf cp sapi/fpm/php-fpm /usr/local/bin
-
Важно, что мы запрещаем Nginx от отправлять запросы в бэкенд PHP-FPM, если файл не
существует, что помогает избежать атаки инъекции скрипта.Мы может исправить это путём установки директивы
cgi.fix_pathinfo
равной0
в нашем php.ini файле.Редактирование php.ini:
vim /usr/local/php/php.ini
Найдите опцию
cgi.fix_pathinfo=
и измените её следующим образом: -
php-fpm.conf должен быть модифицирован, чтобы точно определить, что php-fpm должен
работать под пользователем www-data и группой www-data до того, как мы запустим сервис:vim /usr/local/etc/php-fpm.d/www.conf
Найдите и измените следующее:
; Unix user/group of processes ; Замечание: Пользователь является обязательным. Если группа не установлена, ; то будет использована стандартная группа пользователя. user = www-data group = www-data
Теперь можно запускать сервис php-fpm:
Более в этом руководстве мы не будет касаться настройки php-fpm. Если вам
необходимо произвести дополнительные настройки — обратитесь к документации по php-fpm. -
Теперь 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 ~* .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
-
Создайте тестовый файл
rm /usr/local/nginx/html/index.html echo "<?php phpinfo(); ?>" >> /usr/local/nginx/html/index.php
Теперь откройте в браузере http://localhost. Должна отобразиться информация phpinfo().
Следуя вышеуказанным шагам, вы получите рабочий Nginx сервер с
поддержкой PHP как модуля FPM
SAPI
. Конечно, доступно
большое число опций настроек для Nginx и PHP. Для более
подробной информации наберите ./configure —help
в соответствующем дереве исходных кодов.
Lenny ¶
6 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.
Leon Nguyen vnlab ¶
1 year 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
uanaoeng at outlook dot com ¶
4 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
1097625354 at qq dot com ¶
4 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
610010559 at qq dot com ¶
3 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 .
Akash Kumar Sharma ¶
7 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" .
timy.shark ¶
8 months ago
Great effort for this tutorial, thanks a ton, here are my notes if may help anyone, considering default install on WSL2 container
Note: composer added for Laravel framework.
These are NOT to be copy and pasted as it is, need to be selective as there are annotations beside some commands,
Also I've commented # some of the defaults written by the original editor due to mismatch to my current environment.
sha256sum php-x.x.x.tar.gz => e847745fd66fc8c57fac993a609fefcded93fddccd225f0620a26bb5ae5753c3
tar zxf php-x.x.x
sudo apt install build-essential
sudo apt install -y composer nginx pkgconf libxml2-dev libsqlite3-dev zlib1g-dev
cd php-x.x.x
./configure --enable-fpm --with-mysqli <==Thank you for installing PHP.
make <== takes a while
sudo make test <== optional as recommended
sudo make install <= /usr/local/bin /usr/local/php
sudo cp php.ini-development /usr/local/lib/php.ini
sudo cp /usr/local/etc/php-fpm.d/www.conf.default /usr/local/etc/php-fpm.d/www.conf
sudo cp sapi/fpm/php-fpm /usr/local/bin
sudo vim /usr/local/php/php.ini <= cgi.fix_pathinfo=0
sudo vim /usr/local/etc/php-fpm.d/www.conf <= user=www-data group=www-data
sudo vim sapi/fpm/php-fpm.conf <= edit include=etc/php-fpm.d/*.conf <- relative path
sudo cp sapi/fpm/php-fpm.conf /usr/local/etc
/usr/local/bin/php -v <= $PATH$ uses /usr/local/bin at first /usr/local/lib/php.ini
sudo /usr/local/bin/php-fpm <= start the service
sudo vim /etc/nginx/sites-available/default <= edit the following under server {}
location / {
#root html;
#index index.php index.html index.htm;
}
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;
}
*Restart nginx (root /var/www/html) if root path doesn't exist, default is: /usr/share/nginx/html
sudo nginx -t <= Test Nginx conf files
sudo service nginx reload
sudo service nginx stop
sudo service nginx start <= [OK]
php-fpm needs to be in a service, or kill process manually ps -aux | grep php-fpm ; kill <pid>
nguyentienlong88 at gmail dot com ¶
7 years ago
at step 3, if there is no configure script yet, you need to rebuiding configure script using this command:
./buildconf --force
sp at rysmax dot com ¶
4 years ago
Translate errors:
Теперь перейдите в http://localhsot
Теперь перейдите в http://localhost
В этом разделе описивыется
В этом разделе описывается
запрещаем Nginx от отправлять
запрещаем Nginx отправлять
Hi
Some infos:
* Debian 7.5 * Froxlor 0.9.32 (yay!) * Apache2 2.2.22-13 * PHP5 [FPM] 5.4.4-14
I’ve reinstalled my server today [Debian 7.5, amd64] with Froxlor 0.9.32 (Tarball installation).
So far so good — I having problems with the setup of PHP-FPM…
Panel settings are set (FPM enabled), I’ve leaved the fpm- (path) settings untouched.
The first thing I’ve noticed: After «a2dismod php5» there is a «/etc/init.d/apache2 restart» missing (right?). I did it anyway. While trying to access froxlor again: 500 — Internal server error
php5-fpm.log:
[23-May-2014 21:37:53] ERROR: No pool defined. at least one pool section must be specified in config file [23-May-2014 21:37:53] ERROR: failed to post process the configuration [23-May-2014 21:37:53] ERROR: FPM initialization failed
Whoops…
Then I’ve started some research…
The cronjob created a file @ /etc/php-fpm.d. BUT /etc/php5/fpm/php-fpm.conf say, that the pool is /etc/php5/fpm/pool.d/*.conf and not /etc/php-fpm.d/ (which does not exist as of the latest php5-fpm package) as the defaults are saying that.
Another thing is the default value for the FPM init.d script: default value points to /etc/init.d/php-fpm which not exist. php5-fpm would be right.
However, I did some magic:
cp /etc/php-fpm.d/myhost.conf /etc/php5/fpm/pool.d/ /etc/init.d/php5-fpm restart # and I set the new path for the restart script in phpfpm.reload in panel_settings. Same for the configdir.
And: It’s working again!
So, it seems, that the default values for PHP-FPM for Wheezy are not valid anymore..?
If I forgot something while config, please say it
EDIT: Damn. You already know, that the default value is /etc/php-fpm.d/… -> http://forum.froxlor.org/index.php/topic/12474-solved-500-error-beim-froxlor-panel/?p=25897
I forgot, that the Panel settings are not adjusted while adapting all the configs — right… So, Am I right with the assumption that this value needs to be adjusted for every Debian environment? If yes, a hint in the configuration assistant would be awesome
* The cover image is originally by pixel2013 and edited with great appreciation.
Summary
In OpenBSD, installing PHP by pkg_add
(of ports
) is followed by installing php-fpm automatically. (It’s nice 😃)
However, it doesn’t work as daemon out of the box now in case of PHP 7.2 (and 7.1).
The problem can be fixed by adding its pool definition manually.
This post will show how to do it.
Besides, it is fixed in the -current
version.
* Note: The above links are to Github commits, but The version control system OpenBSD actually uses is CVS.
Environment
- OS: OpenBSD 6.4 amd64
- PHP version: 7.2
✿ ✿ ✿
A Problem
OpenBSD 6.4 has 4 versions of PHP:
# pkg_add php
quirks-3.16 signed on 2018-10-12T15:26:25Z
Ambiguous: choose package for php
a 0: <None>
1: php-5.6.38p0
2: php-7.0.32p1
3: php-7.1.22
4: php-7.2.10
Your choice:
Enter fullscreen mode
Exit fullscreen mode
According to their support terms, PHP 5.6 is almost no longer safe.
So I choose PHP 7.*, especially 7.2:
Your choice: 4
php-7.2.10: ok
Enter fullscreen mode
Exit fullscreen mode
As a result, these files are created in /etc
:
$ ls /etc/php*
/etc/php-7.2.ini /etc/php-fpm.conf
/etc/php-7.2:
/etc/php-7.2.sample:
opcache.ini
Enter fullscreen mode
Exit fullscreen mode
Sadly, php72_fpm
in php-7.2.10
doesn’t work by default:
# rcctl -d start php72_fpm
doing _rc_parse_conf
...
php72_fpm_flags empty, using default ><
doing _rc_parse_conf /var/run/rc.d/php72_fpm
doing _rc_quirks
doing rc_check
php72_fpm
doing rc_start
doing _rc_wait start
doing rc_check
[10-Nov-2018 23:32:18] WARNING: Nothing matches the include pattern '/etc/php-fpm.d/*.conf' from /etc/php-fpm.conf at line 125.
[10-Nov-2018 23:32:18] ERROR: No pool defined. at least one pool section must be specified in config file
[10-Nov-2018 23:32:18] ERROR: failed to post process the configuration
[10-Nov-2018 23:32:18] ERROR: FPM initialization failed
doing _rc_rm_runfile
(failed)
Enter fullscreen mode
Exit fullscreen mode
The Reason
It is because of the lack of «Pool Definintions».
The description is at the bottom of /etc/php-fpm.ini
:
;;;;;;;;;;;;;;;;;;;;
; Pool Definitions ;
;;;;;;;;;;;;;;;;;;;;
; Multiple pools of child processes may be started with different listening
; ports and different management options. The name of the pool will be
; used in logs and stats. There is no limitation on the number of pools which
; FPM can handle. Your system will tell you anyway :)
; Include one or more files. If glob(3) exists, it is used to include a bunch of
; files from a glob(3) pattern. This directive can be used everywhere in the
; file.
; Relative path can also be used. They will be prefixed by:
; - the global prefix if it's been set (-p argument)
; - /usr/local otherwise
include=/etc/php-fpm.d/*.conf
Enter fullscreen mode
Exit fullscreen mode
But there is no /etc/php-fpm.d/*.conf
.
The Solution
Make the directory and the file manually:
# mkdir /etc/php-fpm.d
# touch /etc/php-fpm.d/default.conf
Enter fullscreen mode
Exit fullscreen mode
What should be written in /etc/php-fpm.d/default.conf
?
We can get it by installing (and uninstalling 😜) PHP 7.0 (php-7.0.32p1
) package.
Its /etc/php-fpm.conf
includes the desired pool definition.
The essence of the definition is like this:
;;;;;;;;;;;;;;;;;;;;
; Pool Definitions ;
;;;;;;;;;;;;;;;;;;;;
[www]
user = www
group = www
listen = /var/www/run/php-fpm.sock
listen.owner = www
listen.group = www
listen.mode = 0660
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3
chroot = /var/www
Enter fullscreen mode
Exit fullscreen mode
Also here is the full version as Gist (423 lines with comments).
Writing in /etc/php-fpm.d/default.conf
, the preparation is finished.
The result is:
# rcctl start php72_fpm
(ok)
Enter fullscreen mode
Exit fullscreen mode
OK 😆
✿ ✿ ✿
Happy serving 🕊
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Open
eethann opened this issue
Dec 6, 2013
· 12 comments
Comments
I have installed php-fpm via chef in vagrant using just «add_recipe ‘php-fpm'». The basic install seems to work but the system fails when starting up the service. The error given is:
Starting php-fpm: [06-Dec-2013 07:40:51] ERROR: Unable to globalize '/etc/php-fpm.d/pools/*.conf' (ret=2) from /etc/php-fpm.conf at line 11.
[06-Dec-2013 07:40:51] ERROR: failed to load configuration file '/etc/php-fpm.conf'
[06-Dec-2013 07:40:51] ERROR: FPM initialization failed
I saw that the path of the include directive in php-fpm.conf is wrong, it is currently pointing to /etc/php-fpm.d/pools/*.conf
but there is no pools directory inside /etc/php-fpm.d/
. Changing the include path in the conf file to remote «/pools» allows the service to be started.
which vm box you’ve used?
Same issue here. CentOS6.4, custom build minimal installation but only Chef installed on top of it. Using Epel -repos if that matters.
@eethann @n1koo
Just including the recipe won’t install proper configs. Create another recipe for creating the pool:
include_recipe ‘php-fpm’
php_fpm_pool «www»
Yeah, noticed that. I don’t know why the service is started in the default recipe. Since at that point it shouldn’t actually have any pools. I’m just about to start changing the default action to :nothing. After creating the pool the service is restarted anyways, so that should work.
Looks nice, but doesn’t the fpm process still get started before creating the pools? I’m the process of testing out zabbix, and this how they use it ( https://github.com/laradji/zabbix/blob/master/recipes/web_nginx.rb ).
Afaik, this should be totally legal. No usage of the default www-pool, start php-fpm after that custom pool has been added.
I’m also on CentOS 6.4, provisioning with chef-solo. Spinx’s pull request #27 looks like exactly what I’d need. Will test.
i also got hit this problem that php-fpm is attempted to start before config from lrwp is written down, and thefore whole recipe fails because service php-fpm is not started.
for me the error was:
[12-Dec-2013 14:41:03] WARNING: Nothing matches the include pattern '/etc/php/fpm.d/*.conf' from /etc/php/php-fpm.conf at line 16.
[12-Dec-2013 14:41:03] ERROR: No pool defined. at least one pool section must be specified in config file
[12-Dec-2013 14:41:03] ERROR: failed to post process the configuration
[12-Dec-2013 14:41:03] ERROR: FPM initialization failed
i think the simpliest is action :nothing in recipes/default.rb and rely on notification to start it
glensc
added a commit
to glensc/cookbook-php-fpm
that referenced
this issue
Dec 12, 2013
starting fpm from recipe makes initial installs to fail when config is incomplete. starting fpm service is handled from lrwp notification so starting from recipe is not really neccessary.
Sorry guys, that was my doing. I think that enabling (but not starting) PHP-FPM is ideal, and that a (delayed) notification starts/restarts it when a pool is added. I don’t know about adding a default pool since most folks would probably want to ‘enable false’ it and add their own. The ‘standard’ with cookbooks in general seems to go against auto-adding things you later remove.
ameir: not following what you are saying with your last commit, you mean PR #29 is ok you to be merged?
mabye selinux, execute «setenforce 0» and try again
Not sure if this is relevant for you guys, but I’ve run into this error a lot and there’s no good info anywhere else, so here’s a better tip than «setenforce 0» if you’re on Ubuntu:
sudo aa-complain /usr/local/bin/php-fpm
/usr/local/bin/php-fpm