Nginx入門到實踐

本文是對Nginx常用配置的整理及記錄。

配置文件

  • 目錄 /etc/nginx/nginx.conf
  • 默認配置語法
user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


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;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}
server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

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

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}

默認模塊

  • http_stub_status_module:nginx客戶端狀態

    • 配置語法:stub_status;需寫在location或server下
    location /status {
            stub_status;
        }
    
  • http_sub_module:http內容替換

    • 配置語法
    • sub_filter string replacement
    • sub_filter_last_modified on|off
    • sub_filter_once on|off:是否只替換第一個
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        sub_filter '要替換的內容' '被替換後的內容';
        sub_filter_once off;
    }
    

請求限制

  • 連接頻率限制:limit_conn_module

  • 語法

    • limit_conn_zone key zone=name:size;
    • limit_conn zone number;
  • 請求頻率限制:limit_reg_module

  • 語法

    • limit_req_zone key zone=name:size rate=rate;
    • limit_req zone=name [burst=numer][nodelay];
      • burst保留遺留number數的請求到下一秒執行
limit_conn_zone $binanry_remote_addr zone=conn_zone:1m;
# 同個ip過來請求,每秒只允許一個請求
limit_req_zone $binanry_remote_addr zone=req_zone:1m rate=1r/s;
http {
    server {
   
    location / {
        root   /usr/share/nginx/html;
        limit_conn conn_zone 1;
        limit_conn req_zone;
        limit_conn req_zone burst=3 nodealy;
        index  index.html index.htm;
        }
    }
}
  • 壓測工具:ab(apache bench)
    • ab -n 100 -c 10 http://test.com/ :-n表示請求數,-c表示併發數

訪問限制

  • 基於IP的的訪問控制:http_access_module
  • 語法
    • allow address|CIDR|UNIX:|all;
    • deny address|CIDR|UNIX:|all;
location ~ ^/admin.html {
    root   /usr/share/nginx/html;
    allow all;
    deny  222.122.191.3;
    # deny  222.122.191.0/24;
    index  index.html index.htm;
    }
}
  • 基於用戶的信任登錄:http_auth_basic_module
  • 語法
    • auth_basic string |off;
    • auth_basic_user_file file;
  • 工具htpasswd
location ~ ^/admin.html {
    root   /usr/share/nginx/html;
    auth_basic "Auth access error!input your password!";
    auth_basic_user_file /etc/nginx/auth_conf;
    index  index.html index.htm;
    }
}

靜態資源web服務

  • 靜態資源服務場景-CDN
    • sendfile on|off:文件讀取
    • tcp_nopush on|off:sendfile開啓下才能使用。提高網絡包的傳輸效率
    • tcp_nodelay on|off:keeplive連接下有效,提高網絡包的傳輸實時性
    • gzip on|off:壓縮傳輸
    • gzip_comp_level level;
    • gzip_http_version 1.0|1.1;
    • 壓縮模塊拓展,預讀gzip功能:http_gzip_static_modules,語法gzip_status on|off
  • 瀏覽器緩存
    • expires [modified] time;
    • expires epoch|max|off;
location ~ ^/admin.html {
    root   /usr/share/nginx/html;
    expires 24h;
    index  index.html index.htm;
    }
}
  • 跨域訪問-Access-Control-Allow-Origin
    • add_header name value [always];
location ~ ^/admin.html {
    root   /usr/share/nginx/html;
    add_header Access-Control-Allow-Origin http://www.baidu.com;
    add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;
    }
}
  • 防盜鏈http_refer
  • valid_referers none|blocked|server_names|string;
location ~ .*\.(jpg|png) {
    valid_referers blocked 116.66.111.222 ~/google\./;
    if($invalid_referer) {
        return 403;
    }
    root   /usr/share/nginx/html;
    }
}

代理服務

  • proxy_pass URL;
# 反向代理
location ~ /test_proxy.html$ {
    proxy_pass http://127.0.0.1:8080;
}

location / {
    if($http_x_forwarded_for !~* "^116\.62\.103\.228") {
        return 403;
    }
    root   /usr/share/nginx/html;
    index index.html;
}

# 正向代理
location / {
    proxy_pass http://$http_host$request_uri;
}
  • 緩衝區:proxy_buffering on|off;
  • 跳轉重定向:proxy_redirect default;
  • 頭信息:proxy_set_header field value;
  • 超時:proxy_connect_timeout time;
location / {
    proxy_pass http://127.0.0.1:8080;
    proxy_redirect default;
    
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    
    proxy_connect_timeout 30;
    proxy_send_timeout 60;
    proxy_read_timeout 60;
    
    proxy_buffering on;
    proxy_buffer_size 32k;
    proxy_buffers 4 128k;
    proxy_busy_buffers_size 256k;
    proxy_max_temp_file_size 256k;
}

# 可以把上面的配置參數寫到proxy_params文件中再引用
location / {
    proxy_pass http://127.0.0.1:8080;
    include proxy_params;
}

負載均衡

  • upstream name {…}; 結合proxy_pass;
http {
upstream oden {
    server 116.62.103.222:8001 down; 
    server 116.62.103.222:8002 backup;
    server 116.62.103.222:8003 max_fail=1 fail_timeout=10s;
    server 116.62.103.222:8004 weight = 5;
}
    server {
        listen 80;
        server_name localhost;
        location / {
        proxy_pass http://oden;
        include proxy_params;
        }
    }
}
  • 調度算法
  • 輪詢
  • 加權輪詢,weight越大分配到的機率更高
  • ip_hash:每個請求按訪問IP的hash結果分配,這樣來自同一個IP固定訪問一個後端服務器
  • least_conn:最少鏈接數,哪個機器連接數少就分發
  • url_hash:按照訪問的URL的hash結果分配請求,是每個URL定向到同一個後端服務器
  • hash關鍵數值:hash自定義的key
    • hash key[consistent]
upstream oden {
    ip_hash;
    server 116.62.103.222:8001; 
}

upstream oden {
    hash $request_uri;
    server 116.62.103.222:8001; 
}

緩存服務

  • proxy_cache
  • proxy_cache_path path
  • proxy_cache zone | off
  • proxy_cache_valid[code…] time
  • 緩存維度:proxy_cache_key string
    • $scheme $proxy_host $request_uri
http {
proxy_cache_path /opt/app/cache levels=1:2 keys_zone=oden_cache:10m max_size=10g inactive=60m use_tep_path=off;

upstream oden {
    server 116.62.103.222:8001; 
    server 116.62.103.222:8002;
}
    server {
        listen 80;
        server_name localhost;
    location / {
        proxy_cache oden_cache;
        proxy_pass http://oden;
        # 在這些情況下緩存的時間
        proxy_cache_valid 200 304 12h;
        proxy_cache_valid any 10m;
        proxy_cache_key $host$uri$is_args$args;
        add_header Nginx-Cache "$upstrem_cache_status";
        
        # 發生錯誤時跳到下一臺服務器
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
        
        include proxy_params;
        }
    }
}
  • 清理指定緩存
    • rm -rf緩存目錄內容
    • 第三方拓展模塊ngx_cache_purge
  • 讓部分頁面不緩存
    • proxy_no_cache string;
    • proxy_no_cache
  • 分片請求
    • slice size;

命令

  • 重啓:systemctl restart nginx.service
  • 配置文件語法正確性檢查:nginx -t -c /etc/nginx/nginx.conf
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章