 
		
	
	
		
		Установка Nginx с PHP-FPM и Varnish на CentOS
Varnish Cache — ускоритель веб-приложений также известен как обратный прокси-сервер кэширования HTTP. Итак, вы хотите, чтобы ускорить свой сайт? Я покажу вам, как установить и настроить Varnish с Nginx и PHP-FPM на Centos.
Прежде всего скачайте и установите remi репо и epel репо для этого выполните.
Теперь установим PHP с часто используемыми модулями и PHP-FPM, для этого в терминале выполните:
# yum --enablerepo=remi install php php-fpm php-common php-mysql php-pdo php-pecl-apc php-cli php-mcrypt php-xml php-gd php-mbstring
Теперь нужно установить Nginx
# yum install nginx
Теперь необходимо отредактировать файл конфигурации PHP-FPM и изменить пользователя и группу для Nginx:
# ee /etc/php-fpm.d/www.conf
listen = /var/run/php-fpm/php-fpm.sock user = nginx group = nginx
Отредактируем файл конфигурации Nginx и установим (поменяем) порт на 8080, затем установить (пропишем) правильный путь к файлу сокету PHP-FPM:
# ee /etc/nginx/conf.d/linux-notes.org.conf
Содержание у меня следующее:
server {
listen *:8080;
#listen 127.0.0.1:8080 default; 
server_name linux-notes.org www.linux-notes.org;
#charset koi8-r;
access_log /var/log/nginx/access-linux-notes.org.log main;
error_log /var/log/nginx/error-linux-notes.org.log;
include conf.d/gzip.conf;
root /home/www/linux-notes/public_html;
index index.php index.html index.htm;
#errors
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html/;
}
location / {
try_files $uri $uri/ /index.php?$args;
} 
location ~ (xmlrpc.php|wp-config.php|wp-settings.php|readme.html|license.txt)$ {
return 404;
access_log off;
}
# PHP-FPM
# PHP scripts -> PHP-FPM server listening on 127.0.0.1:9000
location ~ \.php$ {
# The following line prevents malicious php code to be executed through some uploaded file (without php extension, like image)
# This fix shoudn't work though, if nginx and php are not on the same server, other options exist (like unauthorizing php execution within upload folder)
# More on this serious security concern in the "Pass Non-PHP Requests to PHP" section, there http://wiki.nginx.org/Pitfalls
try_files $uri =404;
# PHP 
# NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
fastcgi_pass 127.0.0.1:9000;
fastcgi_cache fastcgicache;
fastcgi_cache_valid any 1m;
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
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_intercept_errors on;
fastcgi_ignore_client_abort off;
fastcgi_connect_timeout 60;
fastcgi_send_timeout 180;
fastcgi_read_timeout 180;
fastcgi_buffers 4 256k;
fastcgi_buffer_size 128k;
fastcgi_busy_buffers_size 256k;
fastcgi_temp_file_write_size 256k;
fastcgi_keep_conn on;
#Помещать страницу в кеш, после 3-х использований. Меньшее число вызвало у меня труднообъяснимые глюки на формах регистрации
fastcgi_cache_min_uses 3;
#Кешировать перечисленные ответы
fastcgi_cache_valid 200 301 302 304 5m;
#Формат ключа кеша - по этому ключу nginx находит правильную страничку
fastcgi_cache_key "$request_method|$host|$request_uri";
}
#----------------------------------------------------------
# Define default caching of 24h
expires 86400s;
add_header Pragma public;
add_header Cache-Control "max-age=86400, public, must-revalidate, proxy-revalidate";
#подключения обработки Perl 
#Все скрипты заканчивающиеся на pl и cgi
# location ~ \.(pl|cgi)$
# {
# #Не сжимаем скрипты
# gzip off;
# try_files $uri =404;
# #Передаем скрипты на обработку fcgiwrap
# fastcgi_pass unix:/var/run/fcgiwrap.socket;
# # Используем стандартные параметры
# include /etc/nginx/fastcgi_params;
# fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
# fastcgi_ignore_client_abort off;
# }
##Замена апачевской ScriptAlias
# location /cgi-bin/ {
# gzip off;
# try_files $uri =404;
# root /var/www/;
# #fastcgi_pass 127.0.0.1:9000;
# fastcgi_pass unix:/var/run/fcgiwrap.socket;
# include /etc/nginx/fastcgi_params;
# fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
# fastcgi_ignore_client_abort off;
# }
#-------
# Rewrite for versioned CSS+JS via filemtime
location ~* ^.+\.(css|js)$ {
rewrite ^(.+)\.(\d+)\.(css|js)$ $1.$3 last;
expires 31536000s;
access_log off;
log_not_found off;
add_header Pragma public;
add_header Cache-Control "max-age=31536000, public";
}
# Aggressive caching for static files
location ~* \.(asf|asx|wax|wmv|wmx|avi|bmp|class|divx|doc|docx|eot|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|mpp|odb|odc|odf|odg|odp|ods|odt|ogg|ogv|otf|pdf|png|pot|pps|ppt|pptx|ra|ram|svg|svgz|swf|tar|t?gz|tif|tiff|ttf|wav|webm|wma|woff|wri|xla|xls|xlsx|xlt|xlw|zip)$ {
expires 31536000s;
access_log off;
log_not_found off;
add_header Pragma public;
add_header Cache-Control "max-age=31536000, public";
}
#----------------------------------------------------------
#/wordpress-w3-total-cache.conf
gzip on;
#gzip_types text/css application/x-javascript text/richtext image/svg+xml text/plain text/xsd text/xsl text/xml image/x-icon;
gzip_types text/css text/x-component application/x-javascript application/javascript text/javascript text/x-js text/richtext image/svg+xml text/plain text/xsd text/xsl text/xml image/x-icon;
#include conf.d/gzip.conf;
location ~ \.(css|js)$ {
expires max;
break;
}
location ~ \.(rtf|rtx|svg|svgz|txt|xsd|xsl|xml)$ {
expires 3600;
break;
}
location ~ \.(asf|asx|wax|wmv|wmx|avi|bmp|class|divx|doc|docx|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|mpp|odb|odc|odf|odg|odp|ods|odt|ogg|pdf|png|pot|pps|ppt|pptx|ra|ram|swf|tar|tif|tiff|wav|wma|wri|xla|xls|xlsx|xlt|xlw|zip)$ {
expires max;
break;
}
add_header "X-UA-Compatible" "IE=Edge,chrome=1";
#---------------------------------------------------------- }
if ($request_method !~ ^(GET|POST|HEAD)$ ) {
return 444;
}
location = /favicon.ico {
log_not_found off;
access_log off;
}
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
# Deny all attempts to access hidden files such as .htaccess, .htpasswd, .DS_Store (Mac).
# Keep logging the requests to parse later (or to pass to firewall utilities such as fail2ban)
location ~ /\.ht {
deny all;
access_log off;
log_not_found off;
}
# Deny access to any files with a .php extension in the uploads directory
# Works in sub-directory installs and also in multisite network
# Keep logging the requests to parse later (or to pass to firewall utilities such as fail2ban)
location ~* /(?:uploads|files)/.*\.php$ {
deny all;
#access_log off;
#log_not_found off;
}
# deny access to WP config file and license.txt and readme.html files
location ~ /(\.|wp-config.php|readme.html|license.txt) {
deny all;
}
# deny access to .conf files
location ~* \.(conf)$ {
deny all;
}
# Add trailing slash to */wp-admin requests.
rewrite /wp-admin$ $scheme://$host$uri/ permanent;
# Uncomment one of the lines below for the appropriate caching plugin (if used).
include global/w3-total-cache.conf;
}
server {
listen 443;
server_name https://linux-notes.org https://www.linux-notes.org;
ssl on;
ssl_certificate /etc/nginx/ssl/linux-notes.org.crt;
ssl_certificate_key /etc/nginx/ssl/linux-notes.org.key;
ssl_session_timeout 5m;
ssl_protocols SSLv2 SSLv3 TLSv1;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
#location / {
# #root html;
# root /home/www/linux-notes/public_html;
# index index.php index.html index.htm;
# }
#
#location ~ \.php$ {
# #root /usr/share/nginx/html;
# root /home/www/linux-notes/public_html;
# fastcgi_split_path_info ^(.+\.php)(.*)$;
# #fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
# include fastcgi_params;
# }
#}
access_log /var/log/nginx/access-linux-notes-SSL.org.log main;
error_log /var/log/nginx/error-linux-notes-SSL.org.log;
include conf.d/gzip.conf;
root /home/www/linux-notes/public_html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ /index.php?$args;
}
# PHP-FPM
# PHP scripts -> PHP-FPM server listening on 127.0.0.1:9000
location ~ \.php$ {
# The following line prevents malicious php code to be executed through some uploaded file (without php extension, like image)
# This fix shoudn't work though, if nginx and php are not on the same server, other options exist (like unauthorizing php execution within up load folder)
# More on this serious security concern in the "Pass Non-PHP Requests to PHP" section, there http://wiki.nginx.org/Pitfalls
try_files $uri =404; 
# PHP 
# NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
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_intercept_errors on;
fastcgi_ignore_client_abort off;
fastcgi_connect_timeout 60;
fastcgi_send_timeout 180;
fastcgi_read_timeout 180;
fastcgi_buffers 4 256k;
fastcgi_buffer_size 128k;
fastcgi_busy_buffers_size 256k;
fastcgi_temp_file_write_size 256k; 
}
#----------------------------------------------------------
# Define default caching of 24h
expires 86400s;
add_header Pragma public;
add_header Cache-Control "max-age=86400, public, must-revalidate, proxy-revalidate"; 
# Rewrite for versioned CSS+JS via filemtime
location ~* ^.+\.(css|js)$ {
rewrite ^(.+)\.(\d+)\.(css|js)$ $1.$3 last;
expires 31536000s;
access_log off;
log_not_found off;
add_header Pragma public;
add_header Cache-Control "max-age=31536000, public";
}
# Aggressive caching for static files
location ~* \.(asf|asx|wax|wmv|wmx|avi|bmp|class|divx|doc|docx|eot|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|mpp|odb|odc|odf|odg|odp|ods|odt|ogg|ogv|otf|pdf|png|pot|pps|ppt|pptx|ra|ram|svg|svgz|swf|tar|t?gz|tif|tiff|ttf|wav|webm|wma|woff|wri|xla|xls|xlsx|xlt|xlw|zip)$ {
expires 31536000s;
access_log off;
log_not_found off;
add_header Pragma public;
add_header Cache-Control "max-age=31536000, public";
}
#----------------------------------------------------------
#/wordpress-w3-total-cache.conf
gzip on;
gzip_types text/css application/x-javascript text/richtext image/svg+xml text/plain text/xsd text/xsl text/xml image/x-icon;
location ~ \.(css|js)$ {
expires max;
break;
}
location ~ \.(rtf|rtx|svg|svgz|txt|xsd|xsl|xml)$ {
expires 3600;
break;
}
location ~ \.(asf|asx|wax|wmv|wmx|avi|bmp|class|divx|doc|docx|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|mpp|odb|odc|odf|odg|odp|ods|odt|ogg|pdf|png|pot|pps|ppt|pptx|ra|ram|swf|tar|tif|tiff|wav|wma|wri|xla|xls|xlsx|xlt|xlw|zip)$ {
expires max;
break;
}
add_header "X-UA-Compatible" "IE=Edge,chrome=1";
#----------------------------------------------------------
location ~ /(\.|wp-config.php|readme.html|license.txt) {
return 404;
}
location = /favicon.ico {
log_not_found off;
access_log off;
}
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
location ~ /\.ht {
deny all;
access_log off;
log_not_found off;
}
}Установим varnish на CentOS
Для того чтобы это сделать нужно добавить репозиторий и выполнить yum команду для установки, сделать это можно так:
Если вы находитесь на совместимый дистрибутив, используйте:
# yum install epel-release
Добавляем репозиторий:
# cd usr/local/src && rpm --nosignature -i https://repo.varnish-cache.org/redhat/varnish-4.1.el7.rpm
Для
# cd usr/local/src && rpm --nosignature -i https://repo.varnish-cache.org/redhat/varnish-4.1.el6.rpm
И собственно, выполняем установку:
# yum install varnish varnish-libs varnish-libs-devel
Нужно поправить файл конфигурации ваниша и задать ему порт 80:
# vim /etc/sysconfig/varnish
Приводим к виду:
#VARNISH_LISTEN_PORT=80 #VARNISH_ADMIN_LISTEN_ADDRESS=127.0.0.1 DAEMON_OPTS="-a 31.187.70.238:80 \ -T localhost:6082 \ -f /etc/varnish/default.vcl \ -S /etc/varnish/secret \ -p thread_pools=4 \ -p thread_pool_max=1500 \ -p listen_depth=2048 \ -p lru_interval=1800 \ -h classic,169313 \ -p obj_workspace=4096 \ -p connect_timeout=600 \ -p max_restarts=6 \ -s file,512M,/var/lib/varnish/varnish_storage.bin" #-s malloc,512m"
ПРИМЕЧАНИЕ: Значение Malloc является «Выделить блок памяти», по этому добавим данный блок памяти:
# vim /etc/varnish/varnish.params
И пропишем:
# Varnish environment configuration description. This was derived from # the old style sysconfig/defaults settings # Set this to 1 to make systemd reload try to switch VCL without restart. RELOAD_VCL=1 # Main configuration file. You probably want to change it. VARNISH_VCL_CONF=/etc/varnish/default.vcl # Default address and port to bind to. Blank address means all IPv4 # and IPv6 interfaces, otherwise specify a host name, an IPv4 dotted # quad, or an IPv6 address in brackets. VARNISH_LISTEN_ADDRESS=31.187.70.238 VARNISH_LISTEN_PORT=80 # Admin interface listen address and port VARNISH_ADMIN_LISTEN_ADDRESS=127.0.0.1 VARNISH_ADMIN_LISTEN_PORT=6082 # Shared secret file for admin interface VARNISH_SECRET_FILE=/etc/varnish/secret # Backend storage specification, see Storage Types in the varnishd(5) # man page for details. VARNISH_STORAGE="malloc,512M" VARNISH_TTL=120 # User and group for the varnishd worker processes VARNISH_USER=varnish VARNISH_GROUP=varnish # Other options, see the man page varnishd(1) #DAEMON_OPTS="-p thread_pool_min=5 -p thread_pool_max=500 -p thread_pool_timeout=300" #
Отредактируем стандартный конфиг и добавим некоторые изменения:
# vim /etc/varnish/default.vcl
Меняем на:
#
# This is an example VCL file for Varnish.
#
# It does not do anything by default, delegating control to the
# builtin VCL. The builtin VCL is called when there is no explicit
# return statement.
#
# See the VCL chapters in the Users Guide at https://www.varnish-cache.org/docs/
# and https://www.varnish-cache.org/trac/wiki/VCLExamples for more examples.
# Marker to tell the VCL compiler that this VCL has been adapted to the
# new 4.0 format.
vcl 4.0;
# Default backend definition. Set this to point to your content server.
backend default {
 .host = "127.0.0.1";
 #.host = "31.187.70.238";
 .port = "8080";
 .probe = {
 .url = "/";
 .interval = 5s;
 .timeout = 1s;
 .window = 5;
 .threshold = 3;
 } 
}
sub vcl_recv {
 # Happens before we check if we have this in cache already.
 #
 # Typically you clean up the request here, removing cookies you don't need,
 # rewriting the request, etc.
}
sub vcl_backend_response {
 # Happens after we have read the response headers from the backend.
 #
 # Here you clean the response headers, removing silly Set-Cookie headers
 # and other mistakes your backend does.
 set beresp.ttl = 10s;
 set beresp.grace = 1h;
 
 # For static content strip all backend cookies and push to static storage
 if (bereq.url ~ "\.(css|js|png|gif|jp(e?)g)|swf|ico") {
 unset beresp.http.cookie;
 set beresp.storage_hint = "static";
 set beresp.http.x-storage = "static";
 } else {
 set beresp.storage_hint = "default";
 set beresp.http.x-storage = "default";
 }
}
sub vcl_deliver {
 # Happens when we have all the pieces we need, and are about to send the
 # response to the client.
 #
 # You can do accounting or modifying the final object here.
}
Вот готовый конфиг, у меня выглядит следующим образом (скачайте его, при необходимости):
# wget linux-notes.org/wp-content/uploads/files/varnish/default.vcl
Или просмотреть его можно тут:
default.vcl
Если вы хотите внести изменения в конфигурацию лаком, проверить изменения конфигурации до перезагрузки лак с помощью следующей команды:
# varnishd -C -f /etc/varnish/default.vcl
И еще один тест:
# varnishd -F -f /etc/varnish/default.vcl bind(): Address already in use bind(): Address already in use child (181964) Started Child (181964) said Child starts
Проверим на корректную работу:
# varnishadm debug.health
и
# GET -HHost:31.187.70.238 http://linux-notes.org -ds 200 OK
Включим логирование для ваниша: Логи важны для любой службы, поэтому мы включим ведение журнала. На примере CentOS 7.
Перезапуск varnishncsa.
# systemctl restart varnishncsa
Перезапуск varnishlog.
# systemctl restart varnishlog
Вы должны увидеть два лог-файла:
# ls -l /var/log/varnish/ total 0 -rw-r--r-- 1 root root 0 May 31 19:17 varnish.log -rw-r--r-- 1 root root 0 May 31 19:17 varnishncsa.log
Добавим еще 1 лог файл:
# varnishncsa -a -w /var/log/varnish/access.log -D -P /var/run/varnishncsa.pid
Теперь вы готовы пойти, начать PHP-FPM, Nginx и ваниш.
Для CentOS/RHEL 6.x и так же Fedora от 15 до 20:
# service php-fpm restart # service nginx restart # service varnish restart
Добавим ваниш в автозагрузку системы следующей командой:
# chkconfig --level 345 varnish on
Для CentOS/RHEL 7.x и Fedora 21
# systemctl restart varnish # systemctl status varnish
Добавим ваниш в автозагрузку системы следующей командой:
# system enable varnish
Добавим (пробросим) нужные порты в iptables:
# vim /etc/sysconfig/iptables
Добавляем
-A INPUT -m state --state NEW -m tcp -p tcp --dport YOUR_PORT -j ACCEPT -A OUTPUT -m state --state NEW -m tcp -p tcp --dport YOUR_PORT -j ACCEPT
Сохраняем файл и перезапускаем iptables:
# service iptables restart
Настроим SELinux ( розрешим подключение на определенный порт):
# vim /etc/selinux/config [...] SELINUX=permissive [...]
Если Вы хотите добавить сервисы nginx php-fpm в автозагрузку, то прочитайте мою статью. На этом установка Nginx с PHP-FPM и Varnish на CentOS завершена.