tiancheng91 / collection

笔记
https://github.com/tiancheng91/collection/issues
22 stars 1 forks source link

nginx 简明教程 #8

Open tiancheng91 opened 6 years ago

tiancheng91 commented 6 years ago

location 匹配

模式 | 含义  匹配范围最小的优先级最高, 由上往下
-- | --
location = /uri | = 表示精确匹配,只有完全匹配上才能生效
location ^~ /uri | ^~ 开头对URL路径进行前缀匹配,并且在正则之前。
location ~ pattern | 开头表示区分大小写的正则匹配
location ~* pattern | 开头表示不区分大小写的正则匹配
location /uri | 不带任何修饰符,也表示前缀匹配,但是在正则匹配之后
location / | 通用匹配,任何未匹配到其它location的请求都会匹配到,相当于switch中的default

基础配置

 root /data/static/;
// 首页
location = / {
}
// 优化静态访问
location ^~ /static/ {
}
location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {
    // 校验refer
    valid_referers none blocked buf.bid;
    if ($invalid_referer) {
       rewrite ^/ http://$host/logo.png;
    }

}
// 默认
location / {
        try_files $uri $uri/ /index.php;
}

配置片段

PHP

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_param SCRIPT_FILENAME $request_filename;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_pass 127.0.0.1:9000;
    }

静态文件

    location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ {
    #    access_log off;
        add_header Cache-Control "public, immutable, max-age=3600000, stale-if-error=3600000, stale-while-revalidate=300";
    }

ssl

add_header Strict-Transport-Security "max-age=15768000; includeSubdomains; preload";

ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4:!DH:!DHiE;
ssl_prefer_server_ciphers on;

# 缓存连接凭证
ssl_session_cache shared:SSL:20m;
ssl_session_tickets on;
ssl_session_timeout 120m;

# OCSP Stapling 服务器段缓存证书链状态信息,避免客户端自己发起验证请求
ssl_stapling on;
ssl_stapling_verify on;
resolver 1.1.1.1 1.0.0.1 valid=3600s;
resolver_timeout 5s;
tiancheng91 commented 6 years ago
// 反代优化 https://www.maxcdn.com/blog/nginx-application-performance-optimization/

worker_processes  auto;
worker_cpu_affinity auto;
worker_rlimit_nofile 65535;
worker_connections 1024; 每个worker建立连接数,server+client

// 默认值
thread_pool default threads=32 max_queue=65536;
thread_pool pool_1 threads=16;
thread_pool pool_2 threads=16;

events {
    // 默认监听一个端口, 通知给所有worker, 所有竞争accept新的连接
    accept_mutex on;       // 打开时 新请求过来时,多个worker串行获取连接, 轮训依赖 accept_mutex_delay
    // reuse_port on;    // 内核3.9以上版本支持, accept_mutex off 优化版本, 多个worker竞争获取连接
}

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

    access_log off;

    // 多块磁盘加速
    proxy_cache_path /mnt/disk1 levels=1:2 keys_zone=cache_1:10m max_size=1024G inactive=60m
                     use_temp_path=off;
    proxy_cache_path /mnt/disk2 levels=1:2 keys_zone=cache_2:10m max_size=1024G 
                     use_temp_path=off;

    // cache参数
    // - levels: 目录层级
    // - keys_zone: 内存中存 缓存key及metadata(计数什么的) 1MB大约存8000个key
    // - max_size: 设置空间上限
    // - inactive: 多长时间未使用从缓存删除, 不同于cache-control里的expired, expired时回触发refreshes
    // - use_temp_path: 禁用temp,nginx默认回先存tmp目录,在复制到具体的缓存目录

    proxy_cache_revalidate on;      // cache-control expired 时, 发起请求带If-Modified-Since 
    proxy_cache_min_uses 3;         // 至少访问几次后才缓存, 防止异常刷磁盘
    proxy_cache_background_update on;
    proxy_cache_lock on;            // 只有MISS时第一个连接回源
    proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
    // 回源异常时使用过期的缓存,对应inactive

    add_header X-Cache-Status $upstream_cache_status;

    // 覆盖默认 cache-control
    proxy_ignore_headers Cache-Control;
    proxy_ignore_headers Set-Cookie;    // 忽略Set-Cookie头
    proxy_cache_methods GET HEAD POST;  // cache哪些请求
    proxy_cache_valid any 30m;

    // 哪些是不需要缓存的,cookies带nocache, 或query带nocache
    proxy_cache_bypass $cookie_nocache $arg_nocache;
    // key规则, 可以cookie按人缓存
    proxy_cache_key $proxy_host$request_uri$cookie_jessionid;

    // A/B测试分组
    split_clients $request_uri $disk {
        80%     1;
        *       2;      // 默认
    }

    server {
        listen 8000;

        location / {
            root /storage;
            aio threads=default;
            sendfile on;
            sendfile_max_chunk 512k;
        }

        upstream backend {
            keepalive 100;
            server 192.168.100.250 weight=1 max_fails=2 fail_timeout=10;
            server 192.168.100.251 weight=1 max_fails=2 fail_timeout=10;
            server 192.168.100.252 weight=1 max_fails=2 fail_timeout=10;
        }
        location /dynamic/ {
           proxy_http_version 1.1;   //  keepalive 依赖1.1
           proxy_set_header Connection "";
           proxy_pass http://backend;
           proxy_buffering off;   // 关闭缓冲区, 动态内容会立刻转发, 优化 Time To First Byte (TTFB).
           // So if TTFB is your goal, make sure that tcp_nodelay is enabled (default) and that tcp_nopush is disabled (default).
       }

        location /cache/ {
            proxy_pass http://backend;
            proxy_cache_key $request_uri;
            proxy_cache cache_$disk;
            aio threads=pool_$disk;
            sendfile on;
        }

        location /skip_cache/ {
            set $skip_cache 0;
            if ($request_method = POST) {
                set $skip_cache 1;
            }

            if ($query_string != "") {
                set $skip_cache 1;
            }

            # Don't cache uris containing the following segments
            if ($request_uri ~* "/wp-admin/|/wp-json/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml") {
                set $skip_cache 1;
            }

            # Don't use the cache for logged in users or recent commenters
            if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") {
                set $skip_cache 1;
            }

            fastcgi_cache_bypass $skip_cache;
            fastcgi_no_cache $skip_cache;
            proxy_cache_bypass $skip_cache;
            proxy_cache_bypass $cookie_nocache $arg_nocache$arg_comment;
            proxy_cache_bypass $http_pragma    $http_authorization;
        }
    }
}
tiancheng91 commented 6 years ago

https://www.gitbook.com/book/moonbingbing/openresty-best-practices

tiancheng91 commented 6 years ago
apt install libpcre3 libpcre3-dev zlib1g-dev openssl libssl-dev libxml2 libxslt1-dev libgeoip-dev libluajit-5.1-dev luajit
git clone https://github.com/alibaba/tengine.git
cd tengine
./configure --prefix=/opt/nginx --with-http_geoip_module=shared    --with-http_mp4_module=shared --with-http_sysguard_module=shared
make
make install

// https://github.com/openresty/lua-nginx-module/pull/1173/files  
// nginx-lua 安装失败, 见上面, lua即将被废弃, 优先使用luajit
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz && gzip -d GeoLiteCity.dat.gz