Optimizing WordPress with Nginx, Varnish, APC, W3 Total Cache

Идеята е ясна – оптимизация на уордпрес блога чрез varnish който работи пред nginx-a с една едничка цел – по-бързо отваряне на сайта ни.

Първо инсталираме nginx и php-fpm :

apt-get install nginx php5-fpm

Ето и примерния ни nginx.conf:

user www-data;
worker_processes 12;

error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;
worker_rlimit_nofile 8192;
events {
worker_connections 4096;
# multi_accept on;
}

http {
include /etc/nginx/mime.types;
# include /etc/nginx/proxy.conf;
include /etc/nginx/fastcgi.conf;
access_log /var/log/nginx/access.log;
upload_progress proxied 1m;
#cache
#fastcgi_cache_path /tmp/cache/fastcgi_cache levels=1:2 keys_zone=php:16m inactive=5m max_size=500m;
proxy_cache_path /var/www/cache/ levels=1:2 keys_zone=алабала.нет:10m inactive=30m max_size=2g;

upstream php5-fpm-sock {
server 127.0.0.1:9000 weight=100 max_fails=3 fail_timeout=5;
#server 127.0.0.1:9001 weight=100 max_fails=3 fail_timeout=5;
#server unix:/var/run/php5-fpm.sock;
}
#sendfile on;
#tcp_nopush on;

#keepalive_timeout 0;
keepalive_timeout 65;
tcp_nodelay on;

gzip on;
gzip_disable “MSIE [1-6]\.(?!.*SV1)”;
gzip_http_version 1.0;
gzip_comp_level 9;
gzip_proxied any;
gzip_min_length 1100;
gzip_buffers 16 8k;
gzip_types text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;

include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
server_tokens on;
server_name_in_redirect off;

}

След това е нужно да създадем виртуален хост за сайта ни – /etc/nginx/sites-enabled/виртуален-хост.лтд


server {
listen 8080;
server_name алабала.нет;

access_log /var/log/nginx/алабала.net.access.log;
error_log /var/log/nginx/алабала.net.error.log;
location / {
root /var/www/blog/;
rewrite ^/wp-content/w3tc/min/([a-f0-9]+)\/(.+)\.(include(\-(footer|body))?(-nb)?)\.[0-9]+\.(css|js)$ /wp-content/w3tc/min/index.php?tt=$1&gg=$2&g=$3&t=$7 last;
# autoindex on;
# autoindex_exact_size off;
index index.php index.html index.htm;
# charset windows-1251;
charset utf-8;
#source_charset koi8-r;

# try_files $uri $uri/ /index.php?$args;
try_files $uri/ $uri /index.php?q=$uri&$args;
port_in_redirect off;
}

location /doc {
root /usr/share;
autoindex on;
allow 127.0.0.1;
deny all;
}

location /images {
root /usr/share;
autoindex on;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /var/www/nginx-default;
}
location ~ \.php$ {
root /var/www/blog/;
#fastcgi_pass 127.0.0.1:9000;
fastcgi_pass php5-fpm-sock;
fastcgi_send_timeout 15;
fastcgi_read_timeout 15;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /var/www/blog/$fastcgi_script_name;
client_max_body_size 900m;
client_body_buffer_size 128k;
track_uploads proxied 30s;

include /etc/nginx/fastcgi_params;
}

location /nginx_status {
stub_status on;
access_log off;
# deny all;
}
root /var/www/blog/;
deny all;
}
# BEGIN W3TC Page Cache cache

location ~ /wp-content/w3tc/pgcache.*html$ {
root /var/www/blog/;

add_header X-Powered-By “W3 Total Cache/0.9.2.4″;
add_header Vary “Accept-Encoding, Cookie”;
}

location ~ /wp-content/w3tc/pgcache.*gzip$ {
root /var/www/blog/;

gzip off;
types {}
default_type text/html;
add_header X-Powered-By “W3 Total Cache/0.9.2.4″;
add_header Vary “Accept-Encoding, Cookie”;
add_header Content-Encoding gzip;
}
# END W3TC Page Cache cache
# BEGIN W3TC Browser Cache
gzip on;
gzip_types text/css application/x-javascript text/x-component text/richtext image/svg+xml text/plain text/xsd text/xsl text/xml image/x-icon;
location ~ \.(css|js|htc)$ {
root /var/www/blog/;

add_header X-Powered-By “W3 Total Cache/0.9.2.4″;
}
location ~ \.(html|htm|rtf|rtx|svg|svgz|txt|xsd|xsl|xml)$ {
root /var/www/blog/;
add_header X-Powered-By “W3 Total Cache/0.9.2.4″;
}
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|otf|odb|odc|odf|odg|odp|ods|odt|ogg|pdf|png
|pot|pps|ppt|pptx|ra|ram|svg|svgz|swf|tar|tif|tiff|ttf|ttc|wav|wma|wri|xla|xls|xlsx|xlt|xlw|zip)$ {
# последните два реда трябва да се съединят и да станат един ред за работи правилно всико.
root /var/www/blog/;
add_header X-Powered-By “W3 Total Cache/0.9.2.4″;
}
# END W3TC Browser Cache
# BEGIN W3TC Minify core
rewrite ^/wp-content/w3tc/min/w3tc_rewrite_test$ /wp-content/w3tc/min/index.php?w3tc_rewrite_test=1 last;
rewrite ^/wp-content/w3tc/min/(.+\.(css|js))$ /wp-content/w3tc/min/index.php?file=$1 last;
# END W3TC Minify core
# BEGIN W3TC Page Cache core
rewrite ^(.*\/)?w3tc_rewrite_test$ $1?w3tc_rewrite_test=1 last;
set $w3tc_rewrite 1;
if ($request_method = POST) {
set $w3tc_rewrite 0;
}
if ($query_string != “”) {
set $w3tc_rewrite 0;
}
if ($http_host != “алабала.net”) {
set $w3tc_rewrite 0;
}
set $w3tc_rewrite2 1;
if ($request_uri !~ \/$) {
set $w3tc_rewrite2 0;
}
if ($request_uri ~* “(sitemap(_index)?\.xml(\.gz)?|[a-z0-9_\-]+-sitemap([0-9]+)?\.xml(\.gz)?)”) {
set $w3tc_rewrite2 1;
}
if ($w3tc_rewrite2 != 1) {
set $w3tc_rewrite 0;
}
set $w3tc_rewrite3 1;
if ($request_uri ~* “(\/wp-admin\/|\/xmlrpc.php|\/wp-(app|cron|login|register|mail)\.php|\/feed\/|wp-.*\.php|index\.php)”) {
set $w3tc_rewrite3 0;
}
if ($request_uri ~* “(wp\-comments\-popup\.php|wp\-links\-opml\.php|wp\-locations\.php)”) {
set $w3tc_rewrite3 1;
}
if ($w3tc_rewrite3 != 1) {
set $w3tc_rewrite 0;
}
if ($http_cookie ~* “(comment_author|wp\-postpass|wordpress_\[a\-f0\-9\]\+|wordpress_logged_in)”) {
set $w3tc_rewrite 0;
}
if ($http_user_agent ~* “(W3\ Total\ Cache/0\.9\.2\.4)”) {
set $w3tc_rewrite 0;
}
set $w3tc_ua “”;
set $w3tc_ref “”;
set $w3tc_ssl “”;
set $w3tc_enc “”;
if ($http_accept_encoding ~ gzip) {
set $w3tc_enc _gzip;
}
set $w3tc_ext “”;
if (-f “$document_root/wp-content/w3tc/pgcache/$request_uri/_index$w3tc_ua$w3tc_ref$w3tc_ssl.html$w3tc_enc”) {
set $w3tc_ext .html;
}
if ($w3tc_ext = “”) {
set $w3tc_rewrite 0;
}
if ($w3tc_rewrite = 1) {
rewrite .* “/wp-content/w3tc/pgcache/$request_uri/_index$w3tc_ua$w3tc_ref$w3tc_ssl$w3tc_ext$w3tc_enc” last;
}
# END W3TC Page Cache core
}

Така , след всичко това трябва да имаме работещ nginx на порт 8080 , от тук нататък идва ред на Varnish.
Първо го инсталираме :

apt-get install varnish

Идват и настройките..
Правим си файл алабала.vcl в директория /etc/varnish/ и пействаме в него това:

backend default {
.host = "127.0.0.1";
.port = "8080";
}
acl purge {
"localhost";
}

sub vcl_recv {
if (req.request == “PURGE”) {
if (!client.ip ~ purge) {
error 405 “Not allowed.”;
}
return(lookup);
}
if (req.url ~ “^/$”) {
unset req.http.cookie;
}
}
sub vcl_hit {
if (req.request == “PURGE”) {
set obj.ttl = 0s;
error 200 “Purged.”;
}
}
sub vcl_miss {
if (req.request == “PURGE”) {
error 404 “Not in cache.”;
}
if (!(req.url ~ “wp-(login|admin)”)) {
unset req.http.cookie;
}
if (req.url ~ “^/[^?]+.(jpeg|jpg|png|gif|ico|js|css|txt|gz|zip|lzma|bz2|tgz|tbz|html|htm)(\?.|)$”) {
unset req.http.cookie;
set req.url = regsub(req.url, “\?.$”, “”);
}
if (req.url ~ “^/$”) {
unset req.http.cookie;
}
}
sub vcl_fetch {
if (req.url ~ “^/$”) {
unset beresp.http.set-cookie;
}
if (!(req.url ~ “wp-(login|admin)”)) {
unset beresp.http.set-cookie;
}
}

След това отваряме /etc/default/varnish и закоментираме всичко като оставяме само :

START=yes

# Maximum number of open files (for ulimit -n)
NFILES=131072

# Maximum locked memory size (for ulimit -l)
# Used for locking the shared memory log in memory. If you increase log size,
# you need to increase this number as well
MEMLOCK=82000

# Default varnish instance name is the local nodename. Can be overridden with
# the -n switch, to have more instances on a single server.
INSTANCE=$(uname -n)
DAEMON_OPTS=”-a ИП.АДРЕСА.НИ:80 \
-T localhost:6082 \
-f /etc/varnish/алабала.vcl \
-S /etc/varnish/secret \
-s file,/var/lib/varnish/$INSTANCE/varnish_storage.bin,1G”

Следва инсталация на apc,memcached :

apt-get install apc memcached php5-memcached

След това инсталираме необходимия плугин за уордпрес -> W3-Total-Cache.
След успешна инсталация са необходими малки настройки.
Първо слагаме отметка на Page Cache,Minify – тук избираме : Minify mode – Manual , Minify Cache Method – Memcached , Object Cache – отметка , Browser Cache – отметка , Enable varnish cache purging – отметка и за сървър слагаме 127.0.0.1
Следва запаметяване и тест дали всичко работи. Конфигурациите са от моя сървър и с тях всичко работи чудесно :)