Переключение сайта в режим NGINX PHP-FPM

15.12.2019

Работа сайта на 1С Битрикс в режиме Apache NGINX PHP-FPM позволяет увеличить производительность системы минимум на 20%.

Режим полезен для высоконагруженных проектов с высоким трафиком и узлами генерирующими множество страниц.

Данная настройка доступна для самостоятельного изменения только на услугах VPS и выделенных серверов. Для изменений в рамках shared-хостинга требуется написать обращение в техническую поддержку с просьбой "изменить конфигурацию для работы сайта в режиме PHP-FPM".

Изменение режима и версии PHP через панель управления хостингом в любой момент времени.

Выбрать необходимую версию PHP можно параметрах WWW-домена:

битрикс смена версии PHP

Для полноценной поддержки сайтом режима PHP-FPM в панели управления хостингом (под root-пользователем) войдите в раздел "www-домены", выберите домен и нажмите кнопку "Конфиг".

Обязательно предварительно скопируйте весь конфигурационный текст и сохраните на компьютере. В случае, если конфигурация будет изменена с ошибками, то будет возможность вернуть первоначальную рабочую версию.

Далее необходимо внести изменения в образец конфигурационного файла (фрагменты для изменения отмечены в тексте):

Обычный режим
Многосайтовость

Используется для запуска сайта без подсайтов (мультисайтинг/многосайтовость).

server {
    server_name site-example.ru www.site-example.ru;
        return 301 https://$server_name$request_uri;
    charset off;
    index index.php index.html;
    disable_symlinks if_not_owner from=$root_path;
    include /etc/nginx/vhosts-includes/*.conf;
    include /etc/nginx/vhosts-resources/site-example.ru/*.conf;
    access_log /var/www/httpd-logs/site-example.ru.access.log;
    error_log /var/www/httpd-logs/site-example.ru.error.log notice;
    ssi on;
    return 301 https://$host:443$request_uri;
    set $root_path /var/www/uXXXXXbtrxXXXXX/data/www/site-example.ru;
    root $root_path;
    gzip on;
    gzip_comp_level 7;
    gzip_disable "msie6";
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript;
    location / {
    error_page 404 = /404.php;
        location ~ [^/]\.ph(p\d*|tml)$ {
            try_files /does_not_exists @php;
        }
        location ~* ^.+\.(jpg|jpeg|gif|png|svg|js|css|mp3|ogg|mpe?g|avi|zip|gz|bz2?|rar|swf)$ {
            expires 7d;
        }
    }
    listen 111.111.111.111:80;
    location @php {
        fastcgi_index index.php;
        fastcgi_param PHP_ADMIN_VALUE "sendmail_path = /usr/sbin/sendmail -t -i -f admin@site-example.ru";
        fastcgi_pass unix:/var/www/php-fpm/uXXXXXbtrxXXXXX.sock;
        fastcgi_split_path_info ^((?U).+\.ph(?:p\d*|tml))(/?.+)$;
        try_files $uri =404;
        include fastcgi_params;
    }
}
server {
        listen 111.111.111.111:443 ssl;
        ssi on;
        gzip on;
        gzip_comp_level 7;
        gzip_disable "msie6";
        gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript;
        server_name site-example.ru www.site-example.ru;
            ssl_certificate "/var/www/httpd-cert/uXXXXXbtrxXXXXX/site-example.ru.crtca";
            ssl_certificate_key "/var/www/httpd-cert/uXXXXXbtrxXXXXX/site-example.ru.key";
 

            ssl_ciphers EECDH:+AES256:-3DES:RSA+AES:!NULL:!RC4;
            ssl_prefer_server_ciphers on;
            ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
            add_header Strict-Transport-Security "max-age=31536000;";
            ssl_dhparam /etc/ssl/certs/dhparam4096.pem;
        charset off;
        #disable_symlinks if_not_owner from=$root_path;
        index index.php;
        root $root_path;
        set $root_path /var/www/uXXXXXbtrxXXXXX/data/www/site-example.ru;
        set $php_sock unix:/var/www/php-fpm/uXXXXXbtrxXXXXX.sock;
        access_log /var/www/httpd-logs/site-example.ru.access.log;
        error_log /var/www/httpd-logs/site-example.ru.error.log notice;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        client_max_body_size 1024M;
        client_body_buffer_size 4M;

        if ($host = 'www.site-example.ru' ) {
              rewrite ^(.*)$ https://site-example.ru$1 permanent;
        }
        location / {
                try_files       $uri $uri/ @bitrix;
        }
        location ~* /upload/.*\.(php|php3|php4|php5|php6|phtml|pl|asp|aspx|cgi|dll|exe|shtm|shtml|fcg|fcgi|fpl|asmx|pht|py|psp|rb|var)$ {
                types {
                        text/plain text/plain php php3 php4 php5 php6 phtml pl asp aspx cgi dll exe ico shtm shtml fcg fcgi fpl asmx pht py psp rb var;
                }
        }
        location ~ \.php$ {
                try_files       $uri @bitrix;
                fastcgi_pass    $php_sock;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_param PHP_ADMIN_VALUE "sendmail_path = /usr/sbin/sendmail -t -i -f admin@site-example.ru";
                include fastcgi_params;
        }
        location @bitrix {
                fastcgi_pass    $php_sock;
                include fastcgi_params;
                fastcgi_param SCRIPT_FILENAME $document_root/bitrix/urlrewrite.php;
                fastcgi_param PHP_ADMIN_VALUE "sendmail_path = /usr/sbin/sendmail -t -i -f admin@site-example.ru";
        }
        location ~* /bitrix/admin.+\.php$ {
                try_files       $uri @bitrixadm;
                fastcgi_pass    $php_sock;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_param PHP_ADMIN_VALUE "sendmail_path = /usr/sbin/sendmail -t -i -f admin@site-example.ru";
                include fastcgi_params;
        }
        location @bitrixadm{
                fastcgi_pass    $php_sock;
                include fastcgi_params;
                fastcgi_param SCRIPT_FILENAME $document_root/bitrix/admin/404.php;
                fastcgi_param PHP_ADMIN_VALUE "sendmail_path = /usr/sbin/sendmail -t -i -f admin@site-example.ru";
        }
        location = /favicon.ico {
                log_not_found off;
                access_log off;
        }
        location = /robots.txt {
                allow all;
                log_not_found off;
                access_log off;
        }
        #
        # block this locations for any installation
        #
        # ht(passwd|access)
        location ~* /\.ht  { deny all; }
        # repositories
        location ~* /\.(svn|hg|git) { deny all; }
        # bitrix internal locations
        location ~* ^/bitrix/(modules|local_cache|stack_cache|managed_cache|php_interface) {
          deny all;
        }
        # upload files
        location ~* ^/upload/1c_[^/]+/ { deny all; }
        # use the file system to access files outside the site (cache)
        location ~* /\.\./ { deny all; }
        location ~* ^/bitrix/html_pages/\.config\.php { deny all; }
        location ~* ^/bitrix/html_pages/\.enabled { deny all; }
        # Intenal locations
        location ^~ /upload/support/not_image   { internal; }
        # Cache location: composite and general site
        location ~* @.*\.html$ {
          internal;
          # disable browser cache, php manage file
          expires -1y;
          add_header X-Bitrix-Composite "Nginx (file)";
        }
        # Player options, disable no-sniff
        location ~* ^/bitrix/components/bitrix/player/mediaplayer/player$ {
          add_header Access-Control-Allow-Origin *;
        }
        # Accept access for merged css and js
        location ~* ^/bitrix/cache/(css/.+\.css|js/.+\.js)$ {
          expires 30d;
          error_page 404 /404.html;
        }
        # Disable access for other assets in cache location
        location ~* ^/bitrix/cache              { deny all; }
        
        # Static content
        location ~* ^/(upload|bitrix/images|bitrix/tmp) {
          expires 30d;
        }
        location  ~* \.(css|js|gif|png|jpg|jpeg|ico|ogg|ttf|woff|eot|otf)$ {
          error_page 404 /404.html;
          expires 30d;
        }
        location = /404.html {
                access_log off ;
        }
}

Используется для запуска дочерних сайтов в мультисайтинге/многосайтовости.

server {
	server_name site-example.ru www.site-example.ru *.site-example.ru;
	charset off;
	index index.php;
	disable_symlinks if_not_owner from=$root_path;
	include /etc/nginx/vhosts-includes/*.conf;
	include /etc/nginx/vhosts-resources/site-example.ru/*.conf;
	access_log /var/www/httpd-logs/site-example.ru.access.log;
	error_log /var/www/httpd-logs/site-example.ru.error.log notice;
	ssi on;
	set $root_path /var/www/uXXXXXbtrxXXXXX/data/www/site-example.ru;
	root $root_path;
	location / {
		location ~ [^/]\.ph(p\d*|tml)$ {
			try_files /does_not_exists @php;
		}
		location ~* ^.+\.(jpg|jpeg|gif|png|svg|js|css|mp3|ogg|mpe?g|avi|zip|gz|bz2?|rar|swf)$ {
			expires 7d;
		}
	}
	listen 111.111.111.111:80;
	location @php {
		fastcgi_index index.php;
		fastcgi_param PHP_ADMIN_VALUE "sendmail_path = /usr/sbin/sendmail -t -i -f info@site-example.ru";
		fastcgi_pass unix:/var/www/php-fpm/uXXXXXbtrxXXXXX.sock;
		fastcgi_split_path_info ^((?U).+\.ph(?:p\d*|tml))(/?.+)$;
		try_files $uri =404;
		include fastcgi_params;
	}
}
server {
	server_name site-example.ru www.site-example.ru *.site-example.ru;
	ssl_certificate "/var/www/httpd-cert/uXXXXXbtrxXXXXX/site-example.ru_le1.crtca";
	ssl_certificate_key "/var/www/httpd-cert/uXXXXXbtrxXXXXX/site-example.ru_le1.key";
	ssl_ciphers EECDH:+AES256:-3DES:RSA+AES:!NULL:!RC4;
	ssl_prefer_server_ciphers on;
	ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
	add_header Strict-Transport-Security "max-age=31536000;";
	ssl_dhparam /etc/ssl/certs/dhparam4096.pem;
	charset off;
	index index.php;
	disable_symlinks if_not_owner from=$root_path;
	include /etc/nginx/vhosts-includes/*.conf;
	include /etc/nginx/vhosts-resources/site-example.ru/*.conf;
	access_log /var/www/httpd-logs/site-example.ru.access.log;
	error_log /var/www/httpd-logs/site-example.ru.error.log notice;
	ssi on;
	set $root_path /var/www/uXXXXXbtrxXXXXX/data/www/site-example.ru;
	root $root_path;

if ($request_uri ~ ^(.*)/index.(html|php)) { return 301 $1/$is_args$args; }
	location / {
	try_files $uri $uri/ /bitrix/urlrewrite.php$is_args$args;
	}

	listen 111.111.111.111:443 ssl http2;

	location @php {
		fastcgi_index index.php;
		fastcgi_param PHP_ADMIN_VALUE "sendmail_path = /usr/sbin/sendmail -t -i -f info@site-example.ru";
		fastcgi_pass unix:/var/www/php-fpm/uXXXXXbtrxXXXXX.sock;
		fastcgi_split_path_info ^((?U).+\.ph(?:p\d*|tml))(/?.+)$;
		try_files $uri =404;
		include fastcgi_params;
	}

	location ~ \.php$ {
	        location ~* /\.\./ { internal; }
	        location ~ /\.[^/]+$ { internal; }
	        location ~* ^/upload/1c_[^/]+/ { internal; }
	        location ~* ^/bitrix/(footer|header|license_key)\.php$ { internal; }
	        location ~* ^/(bitrix|local)/components/(.*)/(.*)/(class|component)\.php$ { internal; }
	        location ~* ^/(bitrix|local)/(backup|blocks|bx_cloud_upload|local_cache|module|modules|managed_cache|php_interface|public|stack_cache)/ { internal; }
	        include /etc/nginx/fastcgi_params;
	        fastcgi_pass unix:/var/www/php-fpm/uXXXXXbtrxXXXXX.sock;
	        fastcgi_index index.php;
	        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
	        fastcgi_intercept_errors on;
	}
}