Hugo博客公告弹窗

nginx缓存配置应对高并发高流量方法

Nginx配置

# FastCGI 缓存全局配置
fastcgi_cache_path /var/cache/nginx/123_com levels=1:2 keys_zone=AADM.COM:200m inactive=8h max_size=10G;
fastcgi_cache_path /var/cache/nginx/456_com levels=1:2 keys_zone=BBDM.ORG:200m inactive=8h max_size=10G;
fastcgi_cache_key "$scheme$request_method$host$request_uri$is_args$args";
fastcgi_cache_use_stale error timeout invalid_header http_500 http_503;
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;

站点1的缓存路径和keys_zone

/var/cache/nginx/123_com  # 路径
keys_zone=AADM.COM        # keys_zone

站点2的缓存路径和keys_zone

/var/cache/nginx/456_com
keys_zone=BBDM.ORG

站点配置

例如站点2

    # 1. 缓存控制块
    set $skip_cache 0;
    if ($request_method = POST) { set $skip_cache 1; }
    if ($query_string != "") { set $skip_cache 1; }
    if ($query_string ~ "^wd=") { set $skip_cache 0; }
    if ($request_uri ~* "purge=all|/wp-admin/|/xmlrpc.php|admin.*\.php|/feed/|index.php|sitemap(_index)?.xml|gbook\.html") { 
        set $skip_cache 1; 
    }
    if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") { 
        set $skip_cache 1; 
    }
	
	
	    # 2. PHP 处理配置
    location ~ [^/]\.php(/|$) {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/tmp/php-cgi-74.sock;
        fastcgi_index index.php;
        include fastcgi.conf;  
        fastcgi_param PATH_INFO $fastcgi_path_info;
        
        # 缓存规则
        fastcgi_cache_bypass $skip_cache;
        fastcgi_no_cache $skip_cache;
        fastcgi_cache BBDM.ORG;
        # 添加这些配置来优化性能
        fastcgi_cache_lock on;           # 防止缓存抖动
        fastcgi_cache_min_uses 1;        # 访问一次就缓存
        fastcgi_cache_revalidate on;     # 使用条件请求
        fastcgi_cache_background_update on; # 后台更新缓存
        fastcgi_cache_valid 200 301 302 8h;
        add_header Nginx-Cache "$upstream_cache_status" always;

        # 安全头部配置块
        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
		#add_header X-Frame-Options SAMEORIGIN;
        add_header X-Content-Type-Options nosniff always;
        add_header X-XSS-Protection "1; mode=block" always;
        add_header Cache-Control "max-age=28800" always;
        add_header Last-Modified $date_gmt always;
        etag on;
    }
	
	
    # 3. 缓存清理配置
    location ~ /purge(/.*) {
        allow 127.0.0.1;
        allow "你的主机IP";
        deny all;
        fastcgi_cache_purge BBDM.ORG "$scheme$request_method$host$1";
    }

CC BY-NC-SA 4.0 转载请注明
最后更新于 2024-11-20 16:13
clarity统计