Welcome! Log In Create A New Profile

Advanced

Кеш nginx работает странно

Posted by webrum 
Кеш nginx работает странно
October 22, 2011 08:45AM
Ситуация такая: на сервере много тяжелых сайтов на друпал, и когда приходит куча индексирующих ботов, сайты открываются очень долго. Я всяко экспериментировал с настройками самого друпала, но пока не нашел лучшего решения, чем сделать кеш веб-страниц через nginx.

Прочитал вот эту статью (http://habrahabr.ru/blogs/hi/72539/), сделал все как в статье, но кеш работает избирательно.
Если я захожу на сайт через браузер, то все работает нормально и в /var/cache/nginx создаются соответствующие файлы. А если я пробую скачать главную страницу сайта с другого сервера через wget, то страница скачивается очень долго и файл в кеше не создается. Я пробовал различные варианты, но кеш работает только если на сайт заходить через браузер.

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

Привожу здесь файлы настройки:

nginx.conf:
----------------
user nginx;
worker_processes 8;
worker_rlimit_nofile 51200;
worker_priority -5;
error_log /var/log/nginx/_error.log;
pid /var/run/nginx.pid;

events {
worker_connections 4096;
use epoll;
}

http {
include /etc/nginx/mime.types;
default_type application/octet-stream;

log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';

access_log /var/log/nginx/_access.log main;

sendfile on;
tcp_nopush on;
tcp_nodelay on;
server_tokens off;
gzip on;
gzip_static on;
gzip_comp_level 5;
gzip_min_length 1024;
gzip_types text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;
keepalive_timeout 65;
limit_zone myzone $binary_remote_addr 10m;
server_names_hash_max_size 32768;

fastcgi_cache_path /var/cache/nginx levels= keys_zone=nginxcache:1024m max_size=20480m inactive=7d;

server {
limit_conn myzone 10;
listen 80;
server_name _;

location / {
root /usr/share/nginx/html;
index index.html index.htm;
}

include standard_errorpages;
}

# Load config files from the /etc/nginx/conf.d directory
include /etc/nginx/conf.d/*.conf;

}
----------------

Файл настройки для сайтов на друпал:
----------------
server {
server_name site1.ru site2.ru site3.ru site4.ru site5.ru

listen 80;
access_log /var/log/nginx/$host.access.log;

set $rootdir /home/sites/www;
root $rootdir;
charset utf-8;

# search for already compressed files
#gzip_static on;
#gzip on;
gzip off;
ssi on;

# some images have no mime type
default_type image/jpeg;

large_client_header_buffers 4 8k;
fastcgi_buffers 256 16k;
fastcgi_buffer_size 64k;
fastcgi_read_timeout 600;
fastcgi_send_timeout 600;
client_max_body_size 10m;

# 404 generated from php can be rather slow. Uncomment with care
#error_page 404 /index.php;

# disallow access to version control directory, but return 404, not to disclose information
location /.git {
return 404;
}

# robots.txt is important for search engines
location = /robots.txt {
access_log off;
}

# This is mostly based on Drupal's stock .htaccess
location ~* ^.+(\.(txt|engine|inc|info|install|module|profile|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)|code-style\.pl|/Entries.*|/Repository|/Root|/Tag|/Template)$ {
return 404;
}

# serve imagecache files directly or redirect to drupal if they do not exist
location ~* imagecache {
access_log off;
expires 30d;
try_files $uri @drupal;
fastcgi_cache off;
}

# Drupal 7 image stylef
location ~* image/generate {
access_log off;
expires 30d;
try_files $uri @drupal;
}

# serve static files directly
location ~* ^.+\.(jpg|jpeg|gif|css|png|js|ico|html|xml|swf|flv)$ {
access_log off;
expires 30d;
}

# This rewrites pages to be sent to PHP processing
location @drupal {
index index.php;
if (!-e $request_filename) {
rewrite ^/(.*)$ /index.php?q=$1 last;
}
}

location / {
try_files $uri @drupal;
}

# This will try to see if we have a boost file in place. no harm done if this is not used
#location @cache {
# queries, drupal cookies, or not GET methods, all require PHP processing.
# if ($query_string ~ ".+") {
# return 405;
# }
# if ($http_cookie ~ "DRUPAL_UID" ) {
# return 405;
# }
# if ($request_method !~ ^(GET|HEAD)$ ) {
# return 405;
# }
# error_page 405 = @drupal;

# Drupal uses 1978 - I am 4 years older than Dries :)
# add_header Expires "Tue, 22 Sep 1974 08:00:00 GMT";
# add_header Cache-Control "must-revalidate, post-check=0, pre-check=0";
# try_files /cache/normal/$host/${uri}_.html /cache/perm/$host/${uri}_.css /cache/perm/$host/${uri}_.js /cache/$host/0$uri.html /cache/$host/0${uri}/index.html @drupal;
# }

# only a few php files are allowed, this increases the overall server security
location ~* ^/(index|boost_stats|cron|xmlrpc).php$ {
fastcgi_pass unix:/var/run/$phpsock.sock;
include fastcgi_params;
fastcgi_param SCRIPT_NAME /index.php;
fastcgi_param SCRIPT_FILENAME $rootdir/$fastcgi_script_name;
fastcgi_param PATH_TRANSLATED $rootdir/$fastcgi_script_name;

fastcgi_cache nginxcache;
fastcgi_cache_valid 200 301 302 304 10080m;
fastcgi_cache_key $request_method|$http_if_modified_since|$http_if_none_match|$host|$request_uri;
fastcgi_hide_header Set-Cookie;
fastcgi_ignore_headers Cache-Control Expires;
}

# internal pages are protected with a simple htpasswd
#location ~* ^/(install|update|memcached|apc|info).php$ {
# auth_basic "Restricted Area";
# auth_basic_user_file htpasswd;
# include fastcgi;
#}

location ~* ^.+\.php$ {
return 404;
}
}

----------------
Re: Кеш nginx работает странно
October 24, 2011 05:39AM
Нашел решение, нужно соответствующую строчку с настройками кеш написать вот так:
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;

После этого только непонятно как можно будет зайти в админку, но хотя бы нагрузка с сервера снялась.
Sorry, you do not have permission to post/reply in this forum.

Online Users

Guests: 116
Record Number of Users: 8 on April 13, 2023
Record Number of Guests: 421 on December 02, 2018
Powered by nginx      Powered by FreeBSD      PHP Powered      Powered by MariaDB      ipv6 ready