nginx: 高性能http和反向代理服務器

一、nginx在應用程序中的做用:

  • 解決跨域
  • 請求過濾
  • 配置gzip
  • 負載均衡
  • 靜態資源服務器

二、基本配置

// nginx.conf.js
events { // 配置nginx與用戶的網絡鏈接
    
}
http { // 配置代理、緩存、日誌定義、配置第三方模塊等
    server { // 配置虛擬主機的參數
        listen 8080,
        server_name: www.baidu.com; //服務端域名
        location / (請求路徑) { // 配置請求路由
            proxy_pass http://0.0.0.0:3000; // 設置代理
        }
        location = *.html {
            root G:/My_Project/Server/index.html; // 獲取靜態文件,注意符號: / 
        }
        location / {
            rewrite ^.*$ / index.html redirect; //精準匹配url,並重定向
        }
    }
    //負載均衡配置
    server {
        listen: 9001;
        server_name: xxx.com;
        location /api {
            proxy_pass http://balanceServer;
        }
    }
    upstream  balanceServer { // 配置後端服務器的具體地址,負載均衡不可或缺
        least_conn;  // 配置鏈接策略
        server 10.132.28.29:3030;
        server 10.132.28.30:3030;
        server 10.132.28.31:3030;
        server 10.132.28.32:3030;
    }
}
gzip                 on;     // on/off(default) 開啓或關閉
gzip_http_version    1.1;    // 須要的最低http版本, 默認http/1.1
gzip_comp_level      5;      // 壓縮級別 1-9(default 1)
gzip_min_length      1000;   // 容許壓縮的最小字節, default 0
gzip_types           text/csv  text/xml  text/css  text/plain  text/javascript  application/javascript
                     application/x-javascript  application/json  application/xml;
                     //壓縮的文件類型,default text/html
複製代碼

三、內置全局變量

變量名 做用
$host 請求信息中的Host
$request_method 請求類型
$remote_addr 客戶端的IP地址
$args 請求參數
$http_cookie 客戶端cookie信息
$remote_port 客戶端端口
$server_addr 服務端地址
$server_name 服務端名稱
$server_port 服務端端口

四、負載均衡策略

  • 輪詢策略(默認): 其中一臺服務器出現延遲,影響全部分配到此服務器的用戶;
  • 最小鏈接數策略(least_conn): 優先分配給壓力較小的服務器;
  • 最快響應時間策略(fair):優先分配給響應時間最短的;
  • 客戶端ip綁定(ip_hash): 同一個ip的請求只分配給一臺服務器,解決網頁session共享問題。
相關文章
相關標籤/搜索