Php fpm fastcgi params

Путь юниксоида

Блог посвященный UNIX-подобным операционным системам.

Настройка FastCGI (PHP FPM) для Nginx

Nginx to CentOS, Debian and Gentoo

FastCGI это высокопроизводительный и масштабируемый интерфейс для взаимодействия веб-сервера и приложений, дальнейшее развитие технологии CGI, однако CGI-скрипты перезапускаются с каждым запросом сервера, что существенно снижает производительность; FastCGI оставляет процессы запущенными и только передает им новые запросы.

nginx имеет собственную поддержку технологии FastCGI для работы с внешними серверами и утилитами. PHP тоже поддерживает FastCGI и может быть использован для обработки FastCGI-запросов от nginx.

В данном примере мы рассмотрим связку nginx и PHP-FPM. Для начала необходимо их установить, в большинстве дистрибутивах для установки есть пакеты с одноимёнными названиями. Или, например в Gentoo, для установки необходим USE флаг fpm , более подробно смотрите в документации к своему дистрибутиву.

Есть много руководств по настройке nginx для работы с PHP FPM, но многие из них являются неполными (неправильно обрабатывается переменная PATH_INFO ) или содержат ошибки в обработке сценариев безопасности (отсутствует проверка наличия PHP кода в php файле).

Настроить подключение nginx и PHP-FPM можно двумя способами — либо через TCP‑порт ( 127.0.0.1:9000 ), либо unix сокет ( /var/run/php-fpm.sock ).

FastCGI параметры

Первая рекомендация — храните все типовые настройки FastCGI в отдельном файле и, при необходимости, импортируйте их.

Например для Debian и Ubuntu настройки по умолчанию находятся в файле /etc/nginx/fastcgi_params , который должен выглядеть следующим образом:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 
fastcgi_param QUERY_STRING $query_string; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param SCRIPT_NAME $fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param REQUEST_URI $request_uri; fastcgi_param DOCUMENT_URI $document_uri; fastcgi_param DOCUMENT_ROOT $document_root; fastcgi_param SERVER_PROTOCOL $server_protocol; fastcgi_param GATEWAY_INTERFACE CGI/1.1; fastcgi_param SERVER_SOFTWARE nginx/$nginx_version; fastcgi_param REMOTE_ADDR $remote_addr; fastcgi_param REMOTE_PORT $remote_port; fastcgi_param SERVER_ADDR $server_addr; fastcgi_param SERVER_PORT $server_port; fastcgi_param SERVER_NAME $server_name; fastcgi_param HTTPS $https; # PHP only, required if PHP was built with --enable-force-cgi-redirect fastcgi_param REDIRECT_STATUS 200;

Подключаем Nginx к PHP FPM

Тут мы должны сказать Nginx`у, чтобы проксировал запросы к PHP FPM через протокол FCGI:

location ~ [^/]\.php(/|$)  fastcgi_split_path_info ^(.+?\.php)(/.*)$; if (!-f $document_root$fastcgi_script_name)  return 404; > fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; >

В параметрах php-fpm.conf за подключение отвечает параметр listen .

# /etc/php/fpm-php5.X/php-fpm.conf . listen = 127.0.0.1:9000 . 

В варианте подключения через unix сокет fastcgi_pass будет таким:

fastcgi_pass unix:/var/run/php5-fpm.sock;

А параметр listen вот так:

# /etc/php/fpm-php5.X/php-fpm.conf . listen = /var/run/php5-fpm.sock . 

После изменения настроек перезапустите nginx.

Тестирование

Создайте файл test.php в корневом каталоге nginx следующего содержания:

В браузере сделайте запрос:

/test.php /test.php/ /test.php/foo /test.php/foo/bar.php /test.php/foo/bar.php?v=1

Обратите внимание на значение REQUEST_URI , SCRIPT_NAME , PATH_INFO и PHP_SELF .

http://example.domain/test.php/foo/bar.php?v=1 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 
array ( 'USER' => 'www-data', 'HOME' => '/var/www', 'FCGI_ROLE' => 'RESPONDER', 'QUERY_STRING' => 'v=1', 'REQUEST_METHOD' => 'GET', 'CONTENT_TYPE' => '', 'CONTENT_LENGTH' => '', 'SCRIPT_FILENAME' => '/var/www/test.php', 'SCRIPT_NAME' => '/test.php', 'PATH_INFO' => '/foo/bar.php', 'REQUEST_URI' => '/test.php/foo/bar.php?v=1', 'DOCUMENT_URI' => '/test.php/foo/bar.php', 'DOCUMENT_ROOT' => '/var/www', 'SERVER_PROTOCOL' => 'HTTP/1.1', 'GATEWAY_INTERFACE' => 'CGI/1.1', 'SERVER_SOFTWARE' => 'nginx/1.4.0', 'REMOTE_ADDR' => '192.168.56.1', 'REMOTE_PORT' => '44644', 'SERVER_ADDR' => '192.168.56.3', 'SERVER_PORT' => '80', 'SERVER_NAME' => '', 'HTTPS' => '', 'REDIRECT_STATUS' => '200', 'HTTP_HOST' => 'lemp.test', 'HTTP_USER_AGENT' => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:20.0) Gecko/20100101 Firefox/20.0', 'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'HTTP_ACCEPT_LANGUAGE' => 'en-US,en;q=0.5', 'HTTP_ACCEPT_ENCODING' => 'gzip, deflate', 'HTTP_CONNECTION' => 'keep-alive', 'PHP_SELF' => '/test.php/foo/bar.php', 'REQUEST_TIME' => 1367829847, )

Необходимые условия:
— Требования к PHP — версия 5.3.3 или выше.
— В php.ini значение cgi.fix_pathinfo = 1 (в некоторых мануалах советуют cgi.fix_pathinfo = 0 что может привести к не правильной обработке переменной PHP_SELF не равной DOCUMENT_URI ).
— Регулярное выражение fastcgi_split_path_info должно корректно обрабатывать запросы, такие как /test.php/foo/blah.php или /test.php/ .
— Необходимо разрешить nginx’у проверку *.php файлов чтобы предотвратить возможность передачи любых других файлов через PHP-FPM (например загруженные картинки).

Ознакомиться с более подробной информацией о FastCGI вы можете на официальном сайте.

Автор — zenon, опубликовано: 11 Июня 2013, 18:54, Вт fastcgi, nginx, php-fpm

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Nginx FastCGI server parameters `fastcgi_param` for PHP FPM (FastCGI Process Manager)

License

WARP-LAB/nginx-fastcgi_params-php

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Nginx FastCGI server parameters fastcgi_param for PHP FPM (FastCGI Process Manager)

Settings for fastcgi_param s server parameters for PHP FPM (FastCGI Process Manager) on Nginx.

  • Adhere to RFC 3875 (further — Standard).
  • Add fastcgi_param entries that are not in Standard, but are required op and security wise.
  • Add parameters that are commonly used mostly because PHP code has relied on exposed Apache server internals over years.
  • Assume that FastCGI runs on the same machine as Nginx instance.

Written on Ubuntu Server 18.04.3 LTS , nginx/1.17.7 , PHP 7.4.1 .

Files in directory fastcgi_params-php

location / < try_files $uri $uri/ /index.php$request_uri; > location ~ [^/]\.php(/|$) < fastcgi_index index.php; fastcgi_split_path_info ^(.+?\.php)(/.*)$; if (!-f $document_root$fastcgi_script_name) < return 404; > include /etc/nginx/fastcgi_params-php/000-core.conf; include /etc/nginx/fastcgi_params-php/001-common.conf; fastcgi_pass unix:/run/php/php7.4-fpm_nginx_nginx_nginx.sock; >

Using try_files $fastcgi_script_name

location / < try_files $uri $uri/ /index.php$request_uri; > location ~ [^/]\.php(/|$) < fastcgi_index index.php; fastcgi_split_path_info ^(.+?\.php)(/.*)$; set $saved_fastcgi_path_info $fastcgi_path_info; # http://trac.nginx.org/nginx/ticket/321 try_files $fastcgi_script_name =404; include /etc/nginx/fastcgi_params-php/000-core.conf; include /etc/nginx/fastcgi_params-php/001-common.conf; fastcgi_param PATH_INFO $saved_fastcgi_path_info; fastcgi_param PATH_TRANSLATED $document_root$saved_fastcgi_path_info; fastcgi_pass unix:/run/php/php7.4-fpm_nginx_nginx_nginx.sock; >

⚠️ The issue is that try_files $fastcgi_script_name clears $fastcgi_path_info . See ticket #321.

  • Redefine fastcgi_param s that rely on $fastcgi_path_info after conf file include using $saved_fastcgi_path_info .
  • It may be impractical to try to track all fastcgi_param s that use $fastcgi_path_info , thus files at fastcgi_params-php/*.conf can use $saved_fastcgi_path_info explicitly.

html/index.php holds some helper code to run.

Nginx variables reference

It will be assumed that Standard is required, although obviously PHP applications can be run without defining all parameters in Standard.

The Common Gateway Interface (CGI) Version 1.1, RFC 3875

For HTTP, if the client request required authentication for external access, then the server MUST set the value (..)

The server MUST set this meta-variable if and only if the request is accompanied by a message-body entity.

If the server receives a request with an attached entity but no Content-Type header field, it MAY attempt to determine the correct content type, otherwise it should omit this meta-variable.

The GATEWAY_INTERFACE variable MUST be set to the dialect of CGI being used by the server to communicate with the script.

The PATH_INFO variable specifies a path to be interpreted by the CGI script. It identifies the resource or sub-resource to be returned by the CGI script, and is derived from the portion of the URI path hierarchy following the part that identifies the script itself.

The server MUST set this variable; if the Script-URI does not include a query component, the QUERY_STRING MUST be defined as an empty string («»).

The REMOTE_ADDR variable MUST be set to the network address of the client sending the request to the server.

The server SHOULD set this variable. If the hostname is not available for performance reasons or otherwise, the server MAY substitute the REMOTE_ADDR value.

The REMOTE_IDENT variable MAY be used (..) The server may choose not to support this feature, or not to request the data for efficiency reasons, or not to return available identity data.

If the client request required HTTP Authentication, then the value of the REMOTE_USER meta-variable MUST be set to the user-ID supplied.

The REQUEST_METHOD meta-variable MUST be set to the method which should be used by the script to process the request.

The SCRIPT_NAME variable MUST be set to a URI path (not URL-encoded) which could identify the CGI script.

The SERVER_NAME variable MUST be set to the name of the server host to which the client request is directed.

The SERVER_PORT variable MUST be set to the TCP/IP port number on which this request is received from the client.

The SERVER_PROTOCOL variable MUST be set to the name and version of the application protocol used for this CGI request.

The SERVER_SOFTWARE meta-variable MUST be set to the name and version of the information server software making the CGI request*

cgi.force_redirect is necessary to provide security running PHP as a CGI under most web servers. Left undefined, PHP turns this on by default. You can turn it off here AT YOUR OWN RISK.
The configuration directive cgi.force_redirect prevents anyone from calling PHP directly with a URL like http://my.host/cgi-bin/php/secretdir/script.php. Instead, PHP will only parse in this mode if it has gone through a web server redirect rule.

httpoxy is a set of vulnerabilities that affect application code running in CGI, or CGI-like environments.

There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here.

It lists thirty eight parameters (excluding argv and argc ).

The path component of the requested URI, such as «/index.html». This notably excludes the query string which is available as its own variable named QUERY_STRING.

Variables to skip from supplied Nginx config

Default Nginx install provides /etc/nginx/fastcgi_params file. As of writing it

  • does not contain some Request Meta-Variables defined in Standard
  • contains variables that are not in Standard, but are more or less commonly used in PHP
  • contains variables that are not in Standard and probably should not be set at all in context of PHP

Источник

Читайте также:  Java запустить несколько потоков одновременно
Оцените статью