- PHP Sockfile Variable
- Nginx, PHP-FPM and .sock Files
- How Nginx Connects to PHP-FPM
- PHP Version Matters
- The $sockfile Variable
- How it Works
- Creating PHP Location Blocks
- Hypothetical
- Step 1. Create the Configuration File
- Step 2. Add your Location Block
- Step 3. Check and Reload Nginx
- Nginx unix socket
- Nginx unix socket, ускорение Nginx в связки с PHP-FPM
- Настройка Nginx
- Настройка FPM
- Php fpm sock nginx
PHP Sockfile Variable
This article will provide some background on Nginx and PHP-FPM configuration, and specifically how sockfiles work on your Nginx servers.
We’ll also look at how to create PHP specific configurations ensure any they persist when changing your websites PHP version.
Nginx, PHP-FPM and .sock Files
Nginx doesn’t run its own server-side language processors for languages such as PHP. This being the case, we need to instead run PHP as its own microservice “PHP-FPM” (FPM stands for FastCGI Process Manager) to be able to host websites that run on PHP and handle any PHP requests.
When a request comes in that requires PHP processing, Nginx will pass this to PHP-FPM, this will be processed to generate what is the equivalent of the static HTML version of the page and pass it to Nginx, which then returns it to the client (for example, the visitor’s browser).
For this to work, Nginx and PHP-FPM need to be able to transfer data back and forth.
How Nginx Connects to PHP-FPM
To connect Nginx and PHP-FPM, PHP-FPM listens for requests from FastCGI on a UNIX domain socket. Nginx uses this socket to pass requests to PHP-FPM via the fastcgi_pass directive.
Here’s an example of a location block that will receive and process PHP requests:
location ~ \.php$ < try_files $uri =404; fastcgi_split_path_info ^(.+\.php)(.*)$; include fastcgi_params; include /etc/nginx/extra.d/*php-context.conf; include /var/www/example.com/nginx/*-php-context.conf; fastcgi_pass unix:/var/run/php/php73-fpm-example.com.sock; >
Here we see the pass to the UNIX php73-fpm-example.com.sock file, which is specific to PHP 7.3.
PHP Version Matters
As each individual version of PHP (7.2, 7.3, 7.4 etc) has its own sock file, this is where the $sockfile variable comes in.
Below we will look at how this works on GridPane, and how you can use it to ensure that if you add your own PHP location blocks, they are not going to need re-creating or cause PHP-FPM to go down if you change your website’s PHP version.
The $sockfile Variable
As each version of PHP has its own unique sock file, whenever a websites PHP version is changed, all Nginx configuration files that use it previously had to be regenerated in order to rewrite the current PHP sock file into place on every fastcgi_pass directive.
The $sockfile variable means that now only one file needs to be regenerated, which has numerous benefits, including ensuring your own PHP location blocks persist when changing PHP versions, and that PHP-FPM isn’t accidentally taken down by overlooking previously created configs.
How it Works
Inside your websites, virtual hosts file exists the following include:
include /var/www/test.com/nginx/*example.com-sockfile.conf;
Side note: You can view your own websites’ virtual host with the following command (switching out site.url for your own domain name):
gp conf nginx show site.url
Inside the file that matches this wildcard, we store the UNIX sock file into an Nginx variable using the Nginx directive set_if_empty. For example:
set_if_empty $sockfile unix:/var/run/php/php73-fpm-example.com.sock;
Now, when the PHP version for a website changes we update this single file.
Now this is stored that in a variable, it simplifies the Nginx configuration templates and they no longer need their fastcgi_pass directive input value editing. Instead, they are static like so:
location ~ \.php$ .
set_if_empty $sockfile php;
fastcgi_pass $sockfile;
.
>
Here we are using set_if_empty again so that if the sock file config doesn’t exist it will set to the default server PHP upstream socket.
The set_if_empty is just insurance though, and the UNIX socket is now passed via the variable $sockfile when it does exist.
Creating PHP Location Blocks
The $sockfile variable allows us to set up our own PHP Location blocks without ever needing to worry about switching PHP versions down the line.
Here’s an example to show this in action.
Hypothetical
You want to use our block PHP execution in the /wp-content directory security measure, with the exception of one specific plugin file.
Step 1. Create the Configuration File
Inside the block wp-content PHP execution security measure, there is this include that we can use to add out location block: /var/www/site.url/nginx/*-before-disable-wp-content-php-main-context.conf . Learn more about the additional measure security plugins here:
Create the file with the following command (replacing “site.url” with your domain name and “pluginname” with a name that makes sense for you):
nano /var/www/site.url/nginx/pluginname-before-disable-wp-content-php-main-context.conf
Step 2. Add your Location Block
Add the following to the file, switching out the example plugin file path with your own:
location ~ /wp-content/plugins/dirty-dirty-plugin/file.php$ try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(.*)$;
include fastcgi_params;
set_if_empty $sockfile php;
fastcgi_pass $sockfile;
>
As we’re using the $sockfile variable, if we change the websites PHP version this configuration will persist and call the correct PHP .sock file.
Ctrl+O and then press Enter to save the file. Then Ctrl+X to exit nano.
Step 3. Check and Reload Nginx
We now need to test our Nginx syntax with:
If there are no errors present, reload Nginx with the following command:
Nginx unix socket
В Nginx unix socket — способ подключения к бэкенду в виде PHP-FPM, позволяющий избежать сетевых запросов и дающий значительный прирост в скорости работы.
Nginx является самым быстрым веб-сервером, но он не может обрабатывать скрипты. Для этого нужен бэкенд. В случае с PHP скриптами роль бэкенда выполняет Apache или PHP-FPM.
С приложениями на Python, Ruby, NodeJS могут использоваться другие серверы приложений.
Рассмотрим случай с PHP-FPM и подключение Nginx к сервису способом, который дает максимальную скорость работы — через unix socket.
Nginx unix socket, ускорение Nginx в связки с PHP-FPM
Использование Unix сокета вместо TCP сокета позволяет работать быстрее за счет отсутствия сетевых запросов (обращений к 127.0.0.1).
Рассмотрим установку на Debian 9, для более свежих версий всё будет работать точно также, изменится только версия PHP. Для дистрибутива FPM сразу запускается на unix socket-е.
Устанавливаем пакеты на новый сервер
Настройка Nginx
Создаем файл виртуального хоста
cd /etc/nginx/sites-available && mcedit fpm
server
listen 80;
server_name fpm.com;
root /var/www/fpm.com;
index index.php index.html;
location /
try_files $uri $uri/ =404;
>
location ~ \.php$
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
# fastcgi_pass 127.0.0.1:9000;
>
В последней секции задано, что при обработке всех файлов с расширением .php запросу нужно направлять на unix сокет unix:/var/run/php/php7.0-fpm.sock.
В случае с TCP эта строк комментируется, с fastcgi_pass 127.0.0.1:9000; знак комментария снимается.
Переключение способа подключения Nginx к PHP-FPM выполняется одной строкой с директивой fastcgi_pass.
Имя fpm.com нужно добавить в файл hosts на сервере если используется это же тестовое имя и нужен такой же резуальтат как в статье.
Строка для добавления в /etc/hosts:
127.0.0.1 fpm.com
С доменом направленным на сервер этого не требуется.
До и после строки добавляем открывающий и закрывающий тэги PHP соответственно
Активируем виртуальный хост
ln -s /etc/nginx/sites-available/fpm /etc/nginx/sites-enabled/
Настройка FPM
PHP-FPM запущен, но в netstat -nltp его не увидеть, потому, что TCP-сокет не используется
u_str LISTEN 0 128 /run/php/php7.0-fpm.sock 17149 * 0
В файле /etc/php/7.0/fpm/pool.d/www.conf директивой listen для FPM задается как запускать службу. Unix сокет или комбинация порта и IP адреса.
Значение всегда можно поменять, что и требуется сделать когда нужен переход с TCP на Unix-сокет. Дополнительно к внесению изменений в Nginx.
listen = /run/php/php7.0-fpm.sock
listen.owner = www-data
listen.group = www-data
Обратившись в браузере к URL, который выбран для тестирования, можно увидеть, что PHP скрипт выполняется.
Это говорит об успешном перенаправлении запросов на /run/php/php7.0-fpm.sock и о том, что конфигурация с Nginx unix socket работает.
Если обращений к серверу много, улучшить производительность позволит тонкая настройка Nginx.
Php fpm sock nginx
- The basics of TOGAF certification and some ways to prepare TOGAF offers architects a chance to learn the principles behind implementing an enterprise-grade software architecture, including.
- Haskell vs. PureScript: The difference is complexity Haskell and PureScript each provide their own unique development advantages, so how should developers choose between these two .
- A quick intro to the MACH architecture strategy While not particularly prescriptive, alignment with a MACH architecture strategy can help software teams ensure application .
- Postman API platform will use Akita to tame rogue endpoints Akita’s discovery and observability will feed undocumented APIs into Postman’s design and testing framework to bring them into .
- How to make use of specification-based test techniques Specification-based techniques can play a role in efficient test coverage. Choosing the right techniques can ensure thorough .
- GitHub Copilot Chat aims to replace Googling for devs GitHub’s public beta of Copilot Chat rolls out GPT-4 integration that embeds a chat assistant into Visual Studio, but concerns .
- Navigate multi-cloud billing challenges Keeping track of cloud bills from multiple clouds or accounts can be complex. Learn how to identify multi-cloud billing .
- 5 Google Cloud cost optimization best practices Cost is always a top priority for enterprises. For those considering Google Cloud, or current users, discover these optimization .
- How to create and manage Amazon EBS snapshots via AWS CLI EBS snapshots are an essential part of any data backup and recovery strategy in EC2-based deployments. Become familiar with how .
- BrightTALK @ Black Hat USA 2022 BrightTALK’s virtual experience at Black Hat 2022 included live-streamed conversations with experts and researchers about the .
- The latest from Black Hat USA 2023 Use this guide to Black Hat USA 2023 to keep up on breaking news and trending topics and to read expert insights on one of the .
- API keys: Weaknesses and security best practices API keys are not a replacement for API security. They only offer a first step in authentication — and they require additional .
- AWS Control Tower aims to simplify multi-account management Many organizations struggle to manage their vast collection of AWS accounts, but Control Tower can help. The service automates .
- Break down the Amazon EKS pricing model There are several important variables within the Amazon EKS pricing model. Dig into the numbers to ensure you deploy the service .
- Compare EKS vs. self-managed Kubernetes on AWS AWS users face a choice when deploying Kubernetes: run it themselves on EC2 or let Amazon do the heavy lifting with EKS. See .