Joomla nginx php fpm

Nginx

Nginx is a lightweight Web server that powers about 33% of Web servers across all domains. Unless you have specific requirements that demand a heavy Web server like Apache, you are much better off using Nginx.

Below are instructions on how to get Joomla! running with PHP FastCGI Example.

Install Nginx

For Ubuntu, run aptitude install Nginx. For other distributions, run the corresponding package manager or see the Nginx Install page.

Install PHP FastCGI

For Gentoo, PHP will run as a FastCGI service (FPM), so the Nginx server will run PHP as a separate process:

# echo "dev-lang/php gd gd2 curl simplexml tokenizer dom tidy sqlite xml fpm cgi" >> /etc/portage/package.use # emerge php

The default settings of PHP-FPM are good for most servers. For special configurations, visit the PHP FPM site.

Configure Nginx

Nginx configuration files reside in:

Here is an sample Nginx configuration file, joomla.conf, that you can reuse over all your Nginx enabled-sites.

server < listen 80; server_name YOUR_DOMAIN; server_name_in_redirect off; access_log /var/log/nginx/localhost.access_log; error_log /var/log/nginx/localhost.error_log info; root PATH_ON_SERVER; index index.php index.html index.htm default.html default.htm; # Support Clean (aka Search Engine Friendly) URLs location / < try_files $uri $uri/ /index.php?$args; ># add global x-content-type-options header add_header X-Content-Type-Options nosniff; # deny running scripts inside writable directories location ~* /(images|cache|media|logs|tmp)/.*\.(php|pl|py|jsp|asp|sh|cgi)$ < return 403; error_page 403 /403_error.html; >location ~ \.php$ < fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include /etc/nginx/fastcgi.conf; ># caching of files location ~* \.(ico|pdf|flv)$ < expires 1y; >location ~* \.(js|css|png|jpg|jpeg|gif|swf|xml|txt)$ < expires 14d; >>

Pay attention to a few things:

  1. The parameter fastcgi_pass is set to 127.0.0.1:9000, corresponding to the port that FPM is configured to listen to. This means you can run the PHP processes on separate servers. On Gentoo, you can find this configuration in the /etc/php/fpm-php5.3/php-fpm.conf/ file.
  1. Don’t forget to replace YOUR_DOMAIN & PATH_ON_SERVER above depending on your domain and the path of Joomla on your server.

GZip Support

If you need GZip compression support, add the following section to the http section of the main Nginx configuration file:

gzip on; gzip_http_version 1.1; gzip_comp_level 6; gzip_min_length 1100; gzip_buffers 4 8k; gzip_types text/plain application/xhtml+xml text/css application/xml application/xml+rss text/javascript application/javascript application/x-javascript gzip_proxied any; gzip_disable "MSIE 4\.";

Sources

Источник

Читайте также:  Как проверить на наличие элемента в массиве python

Joomla nginx php fpm

Шаг 1 — Установка репозитория remi

Для настройки SELinux установим дополнительный пакет

$ sudo yum install policycoreutils

Шаг 2 — Установка и настройка memcached

$ sudo yum install memcached

Разрешаем обращение к memcached в фаерволе :

$ sudo firewall-cmd --permanent --zone=public --add-service=memcached

Разрешаем memcached ходить по сети в SElinux:

$ sudo setsebool -P httpd_can_network_memcache 1

Добавляем memcached в автозагрузку:

$ sudo systemctl enable memcached
$ sudo systemctl start memcached

Шаг 3 — Установка PHP 7.2 в режиме FastCGI

Мы будем использовать PHP в режиме FastCGI сервиса (fpm), то есть nginx будет обращаться к PHP как к отдельному процессу:

$ sudo yum install php72-php-fpm php72-php-common php72-php-pecl-memcache php72-php-opcache php72-php-gd php72-php-mbstring php72-php-mysqlnd php72-php-pdo php72-php-pecl-igbinary php72-php-pecl-msgpack

Настройки по умолчанию подходят для большинства серверов. Для тюнинга настроек, обращайтесь к официальной документации PHP FPM site.

Каталог хранения конфигурационных файлов для нашей версии пхп /etc/opt/remi/php72/

Мы внесём следующие изменения в конфигурационный файл

$ sudo vi /etc/opt/remi/php72/php-fpm.d/www.conf

Изменим группу процесса с apache на nginx:

; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
; will be used.
; RPM: apache user chosen to provide access to the same directories as httpd
user = nginx
; RPM: Keep a group allowed to write in log dir.
group = nginx

Переключим демон на работу с сокетами:

; The address on which to accept FastCGI requests.
; Valid syntaxes are:
; 'ip.add.re.ss:port' - to listen on a TCP socket to a specific IPv4 address on
; a specific port;
; '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
; a specific port;
; 'port' - to listen on a TCP socket to all addresses
; (IPv6 and IPv4-mapped) on a specific port;
; '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
;listen = 127.0.0.1:9000
listen = /var/run/php-fpm/php72-fpm-www.sock

Раскомментируем путь к файлам опкэша, зададим явно путь к логам и ограничение памяти для пхп:

php_value[opcache.file_cache] = /var/opt/remi/php72/lib/php/opcache
php_admin_value[error_log] = /var/log/php-fpm/72-www-error.log
php_admin_flag[log_errors] = on
php_admin_value[memory_limit] = 128M

Шаг 4 — Установка и настройка Nginx

Разрешаем обращение к nginx в фаерволе :

$ sudo firewall-cmd --permanent --zone=public --add-service=http --add-service=https

Разрешаем nginx ходить по сети в SElinux к пхп и базе:

$ sudo setsebool -P httpd_can_network_connect 1
$ sudo setsebool -P httpd_can_network_connect_db 1

Файлы конфигурации nginx хранятся в:
• /etc/nginx/conf.d/ настройки виртуальных хостов и сопутствующие
• /etc/nginx/nginx.conf основной файл конфигурации
Это пример типового файла конфигурации nginx, joomla.conf, который можно использовать для любых сайтов на Joomla.

server listen 80; 
server_name YOUR_DOMAIN;
server_name_in_redirect off;

access_log /var/log/nginx/localhost.access_log;
error_log /var/log/nginx/localhost.error_log info;

root PATH_ON_SERVER;
index index.php index.html index.htm default.html default.htm;
# Support Clean (aka Search Engine Friendly) URLs
location / try_files $uri $uri/ /index.php?$args;
>

# deny running scripts inside writable directories
location ~* /(images|cache|media|logs|tmp)/.*\.(php|pl|py|jsp|asp|sh|cgi)$ return 403;
error_page 403 /403_error.html;
>
location ~ \.php$ fastcgi_pass unix:/var/run/php-fpm/php72-fpm-www.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include /etc/nginx/fastcgi.conf;
>

# caching of files
location ~* \.(ico|pdf|flv)$ expires 1y;
>

location ~* \.(js|css|png|jpg|jpeg|gif|swf|xml|txt)$ expires 14d;
>
>

Обратите особое внимание на 2 момента:
1. Параметр fastcgi_pass установлен на юникс-сокет unix:/var/run/php-fpm/php72-fpm-www.sock , который мы указали в настройках php-fpm. Если вы хотите запускать процессы PHP на других серверах необходимо перенастроить на TCP соединения.
2. Вспомните заменить YOUR_DOMAIN и PATH_ON_SERVER в файле на ваш домен и путь к папке Joomla на сервере.

Читайте также:  Php ошибки включить файл

Шаг 4.1 — Включение поддержки GZip

Настоятельно рекомендуем включить поддержку GZip compression support, добавив следующий код внутрь секции http в основном конфигурационном файле nginx:

gzip on; 
gzip_http_version 1.1;
gzip_comp_level 6;
gzip_min_length 1100;
gzip_buffers 4 8k;
gzip_types text/plain application/xhtml+xml text/css application/xml application/xml+rss text/javascript application/javascript application/x-javascript
gzip_proxied any;
gzip_disable "MSIE 4\.";

Шаг 5 — установка MariaDB

$ sudo yum install mariadb-server

После установки, добавляем демон в автозагрузку:

$ sudo systemctl enable mariadb

Запускаем сервер базы данных:

$ sudo systemctl start mariadb

systemctl не отображает весь вывод команд, результат можно проверить выполнив:

$ sudo systemctl status mariadb

Если MariaDB успешно запустилась, мы получим сообщение «Active: active (running)` с последней линией похожей на:

Oct 10 19:06:20 centos-joomla systemd[1]: Started MariaDB database server.

Шаг 6 — безопасность MariaDB Server

MariaDB включает в свою поставку специальный скрипт, который поволяет сменить некоторые настройки по умолчанию, такие как удалённый вход пользователей и пароли по умолчанию. Для этого выполняем:

$ sudo mysql_secure_installation

Скрипт содержит подробное описание действий для каждого шага. Сначала спрашивается смена пароля root.
Дальнейшие предложения можно принимать нажимая Y и потом ENTER для большинства строк, это удалит доступ неавторизованных пользователей по сети, отключит сетевой вход для root, удалит тестовую базу данных, и перезагрузит таблицы с привилегиями .

Шаг 7 — создание базы и отдельного пользователя для Joomla.

Входим на сервер MariaDB под рутом:


$ mysql -u root –pМОЙПАРОЛЬБЕЗРОБЕЛА

Создаём базу данных myjoomla (смените на своё название):

Создаём польователя joomuser для базы myjoomla и паролем ‘ password ’. Эта команда также даст полные права пользователю на эту базу:

Выйти из mysql, войти в веб-интерфейс установщика joomla, указать в настройках базы данных созданную базу, пользователя и пароль. Провести штатную установку.

На этом установка быстрого и безопасного окружения для Joomla завершена. В настройках кэширования можно указать сервер memcache для хранения кэша и сессий.

Читайте также:  Python ввод числовых данных

Про настройку Joomla c SSL можно прочитать в нашем руководстве.

Источник

Nginx

Nginx is a lightweight Web server that powers about 33% of Web servers across all domains. Unless you have specific requirements that demand a heavy Web server like Apache, you are much better off using Nginx.

Below are instructions on how to get Joomla! running with PHP FastCGI Example.

Install Nginx

For Ubuntu, run aptitude install Nginx. For other distributions, run the corresponding package manager or see the Nginx Install page.

Install PHP FastCGI

For Gentoo, PHP will run as a FastCGI service (FPM), so the Nginx server will run PHP as a separate process:

# echo "dev-lang/php gd gd2 curl simplexml tokenizer dom tidy sqlite xml fpm cgi" >> /etc/portage/package.use # emerge php

The default settings of PHP-FPM are good for most servers. For special configurations, visit the PHP FPM site.

Configure Nginx

Nginx configuration files reside in:

  • /etc/nginx/sites-available/ on Ubuntu (for sites running on that Nginx instance)
  • /etc/nginx/nginx.conf on Gentoo and Raspbian (Debian optimized for Raspberry Pi)

Here is an sample Nginx configuration file, joomla.conf, that you can reuse over all your Nginx enabled-sites.

server < listen 80; server_name YOUR_DOMAIN; server_name_in_redirect off; access_log /var/log/nginx/localhost.access_log; error_log /var/log/nginx/localhost.error_log info; root PATH_ON_SERVER; index index.php index.html index.htm default.html default.htm; # Support Clean (aka Search Engine Friendly) URLs location / < try_files $uri $uri/ /index.php?$args; ># add global x-content-type-options header add_header X-Content-Type-Options nosniff; # deny running scripts inside writable directories location ~* /(images|cache|media|logs|tmp)/.*\.(php|pl|py|jsp|asp|sh|cgi)$ < return 403; error_page 403 /403_error.html; >location ~ \.php$ < fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include /etc/nginx/fastcgi.conf; ># caching of files location ~* \.(ico|pdf|flv)$ < expires 1y; >location ~* \.(js|css|png|jpg|jpeg|gif|swf|xml|txt)$ < expires 14d; >>

Pay attention to a few things:

  1. The parameter fastcgi_pass is set to 127.0.0.1:9000, corresponding to the port that FPM is configured to listen to. This means you can run the PHP processes on separate servers. On Gentoo, you can find this configuration in the /etc/php/fpm-php5.3/php-fpm.conf/ file.
  2. Don’t forget to replace YOUR_DOMAIN & PATH_ON_SERVER above depending on your domain and the path of Joomla on your server.

GZip Support

If you need GZip compression support, add the following section to the http section of the main Nginx configuration file:

gzip on; gzip_http_version 1.1; gzip_comp_level 6; gzip_min_length 1100; gzip_buffers 4 8k; gzip_types text/plain application/xhtml+xml text/css application/xml application/xml+rss text/javascript application/javascript application/x-javascript gzip_proxied any; gzip_disable "MSIE 5\.";

Sources

Источник

Оцените статью