Nginx反向代理和緩存服務功能說明和簡單實現 - 運維筆記


 

一、Nginx反向代理功能
Nginx不僅能作為Web Server,還具有反向代理、負載均衡和緩存的功能。下面就簡單說下這些功能:

1、proxy模塊
nginx通過proxy模塊實現將客戶端的請求代理至上游服務器,此時nginx與上游服務器的連接是通過http協議進行的。nginx在實現反向代理功能時的最重要指令為 proxy_pass,它能夠並能夠根據URI、客戶端參數或其它的處理邏輯將用戶請求調度至上游服務器上(upstream server)。

1.1  proxy_pass URL;
設置后端服務器的協議和地址;這條指令可以設置的協議是“http”或者“https”,而地址既可以使用域名或者IP地址加端口(可選)的形式來定義:

proxy_pass http://localhost:8000/uri/;

如果解析一個域名得到多個地址,所有的地址都會以輪轉的方式被使用。當然也可以使用服務器組來定義多個地址。

如果proxy_pass沒有使用URI,傳送到后端服務器的請求URI一般是客戶端發起的原始URI,如果nginx改變了請求URI,則請求路徑與配置中的路徑的匹配部分將被替換為指令中定義的URI:若nginx接到的請求的uri是/name/a.html

#傳送到后端服務器的URI是/remote/a.html
 location /name/ {
      proxy_pass http://172.16.60.20/remote/;
  }                   
========================================================

#傳送到后端服務器的URI是/name/a.html
location /name/ {
      proxy_pass http://172.16.60.20;
  } 

========================================================
#注意與上面用法的區別,這里地址末尾帶有斜線,實際上被認為定義了URI,該“/”會替換“/name/",傳送到后端服務器的URI是/a.html。
location /name/ {

      proxy_pass http://172.16.60.20/;

   }              

如果使用正則表達式定義路徑,則proxy_pass指令不應使用URI。例如:

location ~ ^/mmb {
  proxy_pass http://www.kevin.com;
    }

 在需要代理的路徑中,使用rewrite指令改變了URI,那么nginx將使用重寫后的URI處理請求,而忽略proxy_pass指令設置的URI。如下面所示的例子中,傳送給上游服務器的URI為/index.php?page=<match>。

location / {
    rewrite /(.*)$ /index.php?page=$1 break;
    proxy_pass http://localhost:8080;
    }

1.2  proxy模塊的其它指令
① proxy_connect_timeout time;
與后端服務器建立連接的超時時間。一般不可能大於75秒;

② proxy_cookie_domain off;
取消當前配置級別的所有proxy_cookie_domain指令;
如果配置,則格式為:proxy_cookie_domain domain replacement(替代),即設置"Set-Cookie"響應頭中的domain屬性的替換文本,其值可以為一個字符串、正則表達式的模式或一個引用的變量;例如:

  proxy_cookie_domain localhost example.org;

瀏覽器對 Cookie 有很多限制,如果 Cookie 的 Domain 部分與當前頁面的 Domain 不匹配就無法寫入。所以如果請求 A 域名,服務器 proxy_pass 到 B 域名,然后 B 服務器輸出 Domian=B 的 Cookie,前端的頁面依然停留在 A 域名上,於是瀏覽器就無法將 Cookie 寫入。

不僅是域名,瀏覽器對 Path 也有限制。我們經常會 proxy_pass 到目標服務器的某個 Path 下,不把這個 Path 暴露給瀏覽器。這時候如果目標服務器的 Cookie 寫死了 Path 也會出現 Cookie 無法寫入的問題。

③ proxy_cookie_path off;
格式"proxy_cookie_path path replacement;",即設置"Set-Cookie"響應頭中的path屬性的替換文本,其值可以為一個字符串、正則表達式的模式或一個引用的變量;例如:

proxy_cookie_path /two/ /;           

若“Set-Cookie”響應頭含有屬性“path=/two/some/uri/”,那么該指令會將這個屬性改寫為“path=/some/uri/”。

④ proxy_hide_header field;
nginx默認不會將"Date"、"Server"、"X-Pad",和"X-Accel-..."響應頭發送給客戶端。該指令則可以設置額外隱藏的響應頭,這些響應頭也不會發送給客戶端。相反的,如果希望允許傳遞某些響應頭給客戶端,可以使用proxy_pass_header指令。

⑤ proxy_set_header field value;
重新定義或者添加發往后端服務器的請求頭。value可以包含文本、變量或者它們的組合。例如:

proxy_set_header X-Real-IP $remote_addr;   #給請求頭中添加客戶端IP
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;   

默認情況下,只有兩個請求頭會被重新定義:
proxy_set_header Host $proxy_host;
proxy_set_header Connection close;

如果某個請求頭的值為空,那么這個請求頭將不會傳送給后端服務器:
proxy_set_header Accept-Encoding "";

⑥ proxy_pass_request_headers on|off;
是否將http首部發往上游服務器

⑦ proxy_pass_request_body on|off;
是否將http請求報文的包體部分發往上游服務器

⑧ proxy_redirect [default|off|redirect replacement];
修改上游服務器傳來的響應頭中的"Location"和"Refresh"字段。例如:

proxy_redirect http://localhost:8000/two/ http://frontend/one/;       

replacement字符串可以省略服務器名:
proxy_redirect http://localhost:8000/two/ /;
此時將使用代理服務器的主域名和端口號來替換。如果端口是80,可以不加。

⑨ proxy_send_timeout time;
在連接斷開之前兩次發送至upstream server的寫操作的最大間隔時長;

⑩ proxy_read_timeout time;
在連接斷開之前兩次從接收upstream server接收讀操作的最大間隔時長;

1.3  proxy模塊的內置變量
① $proxy_host:
后端服務器的主機名和端口;

② $proxy_port:
后端服務器的端口;

③ $proxy_add_x_forwarded_for
將$remote_addr變量值添加在客戶端“X-Forwarded-For”請求頭的后面,並以逗號分隔。 如果客戶端請求未攜帶“X-Forwarded-For”請求頭,$proxy_add_x_forwarded_for變量值將與$remote_addr變量相同

2、upstream模塊
如果有多個上游服務器,我們可以把它們放到一個組中,並且給它們賦予不同的權重和類型,進行負載均衡等,這些功能是由upstream模塊實現的。

2.1  配置語法:

upstream name {
      server address [parameters];
      ...
  }

示例:
upstream web {
    server web1.kevin.com       weight=5;
    server web2.kevin.com:8080;
    server unix:/tmp/web3;
    server backup1.kevin.com:8080   backup;
  }

    server {
    location / {
    proxy_pass http://web;
     }
    }

2.2  uptream使用注意:
① 只能用於http上下文

② 各server只能直接使用IP或主機名,不要加協議

2.3  默認情況下,nginx按加權輪轉的方式將請求代理到各上游服務器。與上游服務器通信的時候,如果出現錯誤,請求會被傳給下一個服務器,直到所有可用的服務器都被嘗試過。如果所有服務器都返回失敗,客戶端將會得到最后通信的那個服務器的(失敗)響應結果。

2.4  地址可以是域名或者IP地址,端口是可選的(默認是80),或者是指定“unix:”前綴的UNIX域套接字的路徑。如果一個域名解析到多個IP,本質上是定義了多個server。

2.5  server后可定義的參數:
① weight=number
設定服務器的權重,默認是1。

② max_fails=number
設定Nginx與服務器通信的嘗試失敗的次數。在fail_timeout參數定義的時間段內,如果失敗的次數達到此值,Nginx就認為服務器不可用。在下一個fail_timeout時間段,服務器不會再被嘗試。失敗的嘗試次數默認是1。設為0就會停止統計嘗試次數,認為服務器是一直可用的。

③ fail_timeout=time
默認是10秒,設定統計失敗嘗試次數的時間段。在這段時間中,服務器失敗次數達到指定的嘗試次數,服務器就被認為不可用。服務器被認為不可用的時間段。

④ backup
標記為備用服務器。當主服務器不可用以后,請求會被傳給這些服務器。

⑤ down
標記服務器永久不可用,可以跟ip_hash指令一起使用

2.6  upstream模塊的其它負載均衡算法(用於upstream上下文):
① ip_hash;
作用同lvs中的sh調度算法,將來自於同一個客戶端的請求始終調度至同一台后端服務器(除了當服務器不可用的時候)

② least_conn;
將請求發送到活動連接數最少的那台服務器。如果這樣的服務器有多台,就嘗試按加權輪循來調度

③ sticky cookie name [expires=time] [domain=domain] [httponly] [secure] [path=path];
session綁定,將來自於同一個客戶端的請求始終調度至同一台后端服務器,從而實現客戶端與后端服務器的session保持。

ip_hash指令無法實現對內網NAT用戶的均衡,而sticky指令可以做到;

◆     sticky工作原理
1. 瀏覽器首次發起請求,請求頭未帶cookie。nginx接收請求,發現請求頭沒有cookie,則以輪詢方式將請求代理給后端服務器。
2. 后端服務器處理完請求,將響應頭和內容返回給nginx。
3. nginx生成cookie,返回給客戶端瀏覽器。cookie的值與后端服務器對應,可能是明文,也可能是md5、sha1等Hash值。
4. 瀏覽器接收請求,並創建cookie。
5. 瀏覽器再次發送請求時,帶上cookie。
6. nginx接收到cookie,直接轉給對應的后端服務器

參數說明:
domain:cookie作用的域名
path:cookie作用的路徑
expires:cookie的過期時長

示例如下:

upstream web {
      server web1.kevin.com;
      server web2.kevin.com;
      sticky cookie srv_id expires=1h domain=.kevin.com path=/;
      }

2.7  health_check [interval=time] [fails=number] [passes=number] [uri=uri] [match=name];
對上游服務器組進行健康狀態檢測,用於location中;

參數說明:
interval=time       #檢測的間隔時長,默認為5秒
fails=number       #連續檢測失敗多少次即認為上游服務器不可用,默認為1次
passes=number  #上游服務器從不可用到可用狀態時需要連續檢測的次數,默認為1次
uri=uri                 #定義用於健康檢測的URI,默認為“/”,即默認檢測目標服務器的主頁
match=name      #指定一段配置來當作檢測條件,默認當響應碼為2XX或3XX時認為上游服務器是可用的

示例如下:

http {
      server {
        ...
        location / {
            proxy_pass http://backend;
            health_check uri=/.health.html match=welcome;
             }
      }

   match welcome {      #match配置段要位於http上下文
      status 200;
      header Content-Type = text/html;
      body ~ "Welcome to nginx!";
      }
}

3、fastcgi模塊
nginx能夠通過fastcgi模塊實現將客戶端的動態文件請求代理至fastcgi server,此時nginx與fastcgi server的通信是通過fastcgi協議進行的

3.1   fastcgi模塊的常用指令
①fastcgi_pass address;
指定fastcgi server的地址和端口,也支持使用unix sock;例如:

fastcgi_pass localhost:9000;
fastcgi_pass 192.168.30.20:9000;
fastcgi_pass unix:/tmp/fastcgi.socket;

②fastcgi_bind address | off;
指定聯系fpm服務器時使用的地址;

③fastcgi_param parameter value [if_not_empty];
定義傳遞給fastcgi server的參數;參數值可以是文本、變量或它們的組合,if_not_empty表示不為空時才傳遞。例如:

fastcgi_param SCRIPT_FILENAME /web/scripts$fastcgi_script_name;

④fastcgi_index name;
默認主頁名;就是當URI中的文件名缺省時,使用此文件名

⑤fastcgi_connect_timeout time;
連接fastcgi服務器的超時時長;

⑥fastcgi_send_timeout time;
向fastcgi服務傳輸數據的超時時長;

3.2  通常建議nginx和fastcgi server(如php-fpm)部署在同一台服務器上,因為二者如果通過網絡通信的話會造成額外的性能開銷。

3.3   配置示例

  location ~ \.php$ {
          fastcgi_pass 127.0.0.1:9001;
          fastcgi_index index.php;
          fastcgi_param SCRIPT_FILENAME /web/scripts$fastcgi_script_name;
          include fastcgi_params;
       }

說明:
①參數SCRIPT_FILENAME保存是的腳本文件的絕對路徑;例如,若請求的URI是/test/status.php,那么向fastcgi server傳遞的腳本文件路徑就是/web/scripts/test/status.php
②nginx有兩個文件fastcgi_params和fastcgi.conf,它們存放着nginx向fastcgi server傳遞的參數,二者唯一的區別是后者比前者多了一行 SCRIPT_FILENAME 的定義:
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

3.4  通過nginx查看后端php-fpm的運行狀態

# vim /etc/php-fpm.d/www.conf(若php-fpm是編譯安裝,則為主配置文件)
pm.status_path = fpm_status
ping.path = fpm_ping

# vim /etc/nginx/nginx.conf           
location ~* /(fpm_status|fpm_ping) {
    root           /www/a.com;
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_param  SCRIPT_FILENAME  $fastcgi_script_name;
    include      fastcgi_params;

  }        

二、nginx的緩存功能
nginx做為反向代理時,能夠將來自上游服務器的響應緩存至本地,並在后續的客戶端請求同樣內容時直接從本地構造響應報文。nginx使用磁盤做緩存;

緩存將遵從上游服務器的響應報文首部中關於緩存的設定,如 "Expires"、"Cache-Control: no-cache"、 "Cache-Control: max-age=XXX"、"private"和"no-store" 等,但nginx在緩存時不會考慮響應報文的"Vary"首部。為了確保私有信息不被緩存,所有關於用戶的私有信息可以在上游服務器上通過"no-cache" or "max-age=0"來實現,也可在nginx設定proxy_cache_key必須包含用戶特有數據如$cookie_xxx的方式實現,但最后這種方式在公共緩存上使用可能會有風險。因此,在響應報文中含有以下首部或指定標志的報文將不會被緩存。

Set-Cookie
Cache-Control containing "no-cache", "no-store", "private", or a "max-age" with a non-numeric or 0 value

Expires with a time in the past
X-Accel-Expires: 0

與緩存有關的指令:
① proxy_cache zone | off;
定義一個用於緩存的共享內存區域,其可被多個地方調用;

② proxy_cache_key string;
設定在存儲及檢索緩存時用於“鍵”的字符串,可以使用變量為$uri其值,但使用不當時有可能會為同一個內容緩存多次;另外,將用戶私有信息用於鍵可以避免將用戶的私有信息返回給其它用戶;

例如:proxy_cache_key "$host$request_uri;

③ proxy_cache_lock on | off;
啟用此項,可在緩存未命令中阻止多個相同的請求同時發往upstream,其生效范圍為worker級別;

④ proxy_cache_lock_timeout time;
proxy_cache_lock功能的鎖定時長;

⑤ proxy_cache_min_uses number;
某響應報文被緩存之前至少應該被請求的次數;

⑥ proxy_cache_path path [levels=levels] keys_zone=name:size [inactive=time] [max_size=size] [loader_files=number] [loader_sleep=time] [loader_threshold=time] ;
定義一個用記保存緩存響應報文的目錄,及一個保存緩存對象的鍵及響應元數據的共享內存區域(keys_zone=name:size),其可選參數有:
levels:   每級子目錄名稱的長度,有效值為1或2,每級之間使用冒號分隔,最多為3級;
inactive:非活動緩存項從緩存中剔除之前的最大緩存時長;
max_size:   緩存空間大小的上限,當需要緩存的對象超出此空間限定時,緩存管理器將基於LRU算法對其進行清理;
loader_files:緩存加載器的每次工作過程最多為多少個文件加載元數據;
loader_sleep:  緩存加載器的每次迭代工作之后的睡眠時長;
loader_threashold:  緩存加載器的最大睡眠時長;

示例:
proxy_cache_path /data/nginx/cache/one levels=1 keys_zone=one:10m;
proxy_cache_path /data/nginx/cache/two levels=2:2 keys_zone=two:100m;          

⑦ proxy_cache_use_stale error | timeout | invalid_header | updating | http_500 | http_502 | http_503 |http_504 | http_403 | http_404 | off ...;
在無法聯系到upstream服務器時的哪種情形下(如error、timeout或http_500等)讓nginx使用本地緩存的過期的緩存對象直接響應客戶端請求;

⑧ proxy_cache_valid [code ...] time;
用於為不同的響應設定不同時長的有效緩存時長

例如:
proxy_cache_valid  200 302  10m;

⑨ proxy_cache_methods GET | HEAD | POST ...;
為哪些請求方法啟用緩存功能;

⑩ proxy_cache_bypass string;
設定在哪種情形下,nginx將不從緩存中取數據。

proxy_cache_bypass $cookie_nocache $arg_nocache $arg_comment;
proxy_cache_bypass $http_pragma $http_authorization;

nginx也可將后端fastcgi server的響應結果緩存:

fastcgi_cache
fastcgi_cache_path
fastcgi_cache_valid
...

三、Nginx反向代理簡單實現
負載機:A機器:103.110.186.8/192.168.1.8
后端機器1:B機器:192.168.1.102
后端機器2:C機器:192.168.1.103

需求:
->  訪問A機器的8080端口,反向代理到B機器的8080端口;
->  訪問A機器的8088端口,反向代理到C機器的8088端口;
->  訪問http://103.110.86.8:8090/ios,反向代理到B機器http://192.168.1.102:8090/ios/
->  訪問A機器的80端口,負載均衡到后端的兩台機器B和C的80端口

操作記錄如下:

=========================================================================================
負載機:A機器上的操作記錄:

1)編譯安裝nginx
[root@opd ~]# yum install -y pcre* openssl* gcc gcc+
[root@opd ~]# cd /opt/src
[root@src ~]# wget http://nginx.org/download/nginx-1.8.0.tar.gz
[root@src ~]# tar -zxvf nginx-1.8.0.tar.gz
[root@src ~]# cd nginx-1.8.0
#添加www用戶,其中-M參數表示不添加用戶家目錄,-s參數表示指定shell類型

[root@nginx-1.8.0 ~]#useradd www -M -s /sbin/nologin
[root@nginx-1.8.0 ~]#vim auto/cc/gcc
#將這句注釋掉 取消Debug編譯模式 大概在179行
#CFLAGS="$CFLAGS -g"

#我們再配置下nginx編譯參數
[root@nginx-1.8.0 ~]# ./configure --prefix=/opt/nginx --user=www --group=www --with-http_stub_status_module --with-http_ssl_module
[root@nginx-1.8.0 ~]#make
[root@nginx-1.8.0 ~]#make install clean

2)配置nginx
[root@nginx-1.8.0 ~]# cd /opt/nginx/conf
[root@nginx-1.8.0 conf]# vim nginx.conf         //這個可以作為nginx安裝后的配置規范
http {
    include       mime.types;
    default_type  application/octet-stream;
    charset utf-8;
  
    log_format  main  '$http_x_forwarded_for $remote_addr $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_cookie" $host $request_time';
    sendfile       on;
    tcp_nopush     on;
    tcp_nodelay    on;
    keepalive_timeout  65;
  
  
    fastcgi_connect_timeout 3000;
    fastcgi_send_timeout 3000;
    fastcgi_read_timeout 3000;
    fastcgi_buffer_size 256k;
    fastcgi_buffers 8 256k;
    fastcgi_busy_buffers_size 256k;
    fastcgi_temp_file_write_size 256k;
    fastcgi_intercept_errors on;
   
      
    client_header_timeout 600s;
    client_body_timeout 600s;
   
    client_max_body_size 100m;            
    client_body_buffer_size 256k;          
   
    gzip  on;
    gzip_min_length  1k;
    gzip_buffers     4 16k;
    gzip_http_version 1.1;
    gzip_comp_level 9;
    gzip_types       text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php;
    gzip_vary on;
   
  
    include vhosts/*.conf;
}

[root@nginx-1.8.0 conf]# ulimit -n 65535
[root@nginx-1.8.0 conf]# mkdir vhosts
[root@nginx-1.8.0 conf]# cd vhosts

配置反向代理和負載均衡
[root@nginx-1.8.0 vhosts]# vim 8080.conf
server {
    listen 8080;
    server_name localhost;
    index index.html index.php index.htm;
    root /var/www/html;
  
    access_log  /usr/local/nginx/logs/8080-access.log main;
    error_log  /usr/local/nginx/logs/8080-error.log;
 
location / {
    proxy_pass http://192.168.1.102:8080;
    proxy_redirect off ;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header REMOTE-HOST $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_connect_timeout 300;             #跟后端服務器連接超時時間,發起握手等候響應時間
    proxy_send_timeout 300;                #后端服務器回傳時間,就是在規定時間內后端服務器必須傳完所有數據
    proxy_read_timeout 600;                #連接成功后等待后端服務器的響應時間,已經進入后端的排隊之中等候處理
    proxy_buffer_size 256k;                #代理請求緩沖區,會保存用戶的頭信息以供nginx進行處理
    proxy_buffers 4 256k;                  #同上,告訴nginx保存單個用幾個buffer最大用多少空間
    proxy_busy_buffers_size 256k;          #如果系統很忙時候可以申請最大的proxy_buffers
    proxy_temp_file_write_size 256k;       #proxy緩存臨時文件的大小
    proxy_next_upstream error timeout invalid_header http_500 http_503 http_404;
    proxy_max_temp_file_size 128m;
}
}

[root@nginx-1.8.0 vhosts]# cat 8088.conf
server {
    listen 8088;
    server_name localhost;
    index index.html index.php index.htm;
    root /var/www/html;
  
    access_log  /usr/local/nginx/logs/8088-access.log main;
    error_log  /usr/local/nginx/logs/8088-error.log;
 
location / {
    proxy_pass http://192.168.1.103:8088;
    proxy_redirect off ;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header REMOTE-HOST $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_connect_timeout 300;            
    proxy_send_timeout 300;              
    proxy_read_timeout 600;              
    proxy_buffer_size 256k;               
    proxy_buffers 4 256k;                 
    proxy_busy_buffers_size 256k;        
    proxy_temp_file_write_size 256k;      
    proxy_next_upstream error timeout invalid_header http_500 http_503 http_404;
    proxy_max_temp_file_size 128m;
}
}


》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》
下面這個匹配path的代理設置需要注意幾點:
首先一定要保證目標B機器,也就是192.168.1.102的8090端口站點目錄下有這個匹配path的目錄ios存在!!
也就是要保證A機器本機能順利訪問到目標B機器的8090端口的ios路徑,即:
[root@nginx-1.8.0 vhosts]# curl http://192.168.1.102:8090/ios/ #一定要保證這個能從A機器訪問成功!

下面幾種配置都是可以的:

第一種:
[root@nginx-1.8.0 vhosts]# cat 8090.conf
server {
    listen 8090;
    server_name localhost;
    index index.html index.php index.htm;
    root /var/www/html;
  
    access_log  /usr/local/nginx/logs/8090-access.log main;
    error_log  /usr/local/nginx/logs/8090-error.log;
 
    location /ios/ {                            #這種情況,這里一定要匹配的是/ios/,不能是/ios
    proxy_pass http://192.168.1.102:8090;       #一定要保證192.168.1.102機器8090端口站點目錄下有ios目錄!否則訪問會報錯404!
    proxy_redirect off ;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header REMOTE-HOST $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_connect_timeout 300;            
    proxy_send_timeout 300;              
    proxy_read_timeout 600;              
    proxy_buffer_size 256k;               
    proxy_buffers 4 256k;                 
    proxy_busy_buffers_size 256k;        
    proxy_temp_file_write_size 256k;      
    proxy_next_upstream error timeout invalid_header http_500 http_503 http_404;
    proxy_max_temp_file_size 128m;
}
}

第二種:
[root@nginx-1.8.0 vhosts]# cat 8090.conf
server {
    listen 8090;
    server_name localhost;
    index index.html index.php index.htm;
    root /var/www/html;
  
    access_log  /usr/local/nginx/logs/8090-access.log main;
    error_log  /usr/local/nginx/logs/8090-error.log;
 
    location /ios/ {
    proxy_pass http://192.168.1.102:8090/ios/;
    proxy_redirect off ;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header REMOTE-HOST $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_connect_timeout 300;            
    proxy_send_timeout 300;              
    proxy_read_timeout 600;              
    proxy_buffer_size 256k;               
    proxy_buffers 4 256k;                 
    proxy_busy_buffers_size 256k;        
    proxy_temp_file_write_size 256k;      
    proxy_next_upstream error timeout invalid_header http_500 http_503 http_404;
    proxy_max_temp_file_size 128m;
}
}

第三種:
[root@nginx-1.8.0 vhosts]# cat 8090.conf
server {
    listen 8090;
    server_name localhost;
    index index.html index.php index.htm;
    root /var/www/html;
  
    access_log  /usr/local/nginx/logs/8090-access.log main;
    error_log  /usr/local/nginx/logs/8090-error.log;
 
    location /ios {
    proxy_pass http://192.168.1.102:8090/ios/;         這種情況,這里一定要匹配的是/ios/,不能是/ios
    proxy_redirect off ;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header REMOTE-HOST $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_connect_timeout 300;            
    proxy_send_timeout 300;              
    proxy_read_timeout 600;              
    proxy_buffer_size 256k;               
    proxy_buffers 4 256k;                 
    proxy_busy_buffers_size 256k;        
    proxy_temp_file_write_size 256k;      
    proxy_next_upstream error timeout invalid_header http_500 http_503 http_404;
    proxy_max_temp_file_size 128m;
}
}

以上三種配置方法都保證了訪問http://103.110.86.8:8090/ios會自動變為http://103.10.86.8:8090/ios/,並代理到http://192.168.1.102:8090/ios/的結果

[root@nginx-1.8.0 vhosts]# cat LB.conf
upstream lb {
    server 192.168.1.102:80 max_fails=3 fail_timeout=30s;   #max_fails = 3 為允許失敗的次數,默認值為1
    server 192.168.1.103:80 max_fails=3 fail_timeout=30s;   #fail_timeout = 30s 當max_fails次失敗后,暫停將請求分發到該后端服務器的時間
}
 
server {
    listen 80;
    server_name localhost;
    index index.html index.php index.htm;
    root /var/www/html;
  
    access_log  /usr/local/nginx/logs/80-access.log main;
    error_log  /usr/local/nginx/logs/80-error.log;
 
    location / {
    proxy_pass http://lb;
    proxy_redirect off ;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header REMOTE-HOST $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_connect_timeout 300;            
    proxy_send_timeout 300;              
    proxy_read_timeout 600;              
    proxy_buffer_size 256k;               
    proxy_buffers 4 256k;                 
    proxy_busy_buffers_size 256k;        
    proxy_temp_file_write_size 256k;      
    proxy_next_upstream error timeout invalid_header http_500 http_503 http_404;
    proxy_max_temp_file_size 128m;
}
}

啟動nginx
[root@nginx-1.8.0 vhosts]# /opt/nginx/sbin/nginx -t 
nginx: the configuration file /opt/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /opt/nginx/conf/nginx.conf test is successful

[root@host-192-168-1-102 vhosts]# /opt/nginx/sbin/nginx 

=====================================================================================
后端機:B機器上的操作記錄:

1)編譯安裝nginx
[root@B ~]# yum install -y pcre* openssl* gcc gcc+
[root@B ~]# cd /opt/src
[root@B ~]# wget http://nginx.org/download/nginx-1.8.0.tar.gz
[root@B ~]# tar -zxvf nginx-1.8.0.tar.gz
[root@B ~]# cd nginx-1.8.0
#添加www用戶,其中-M參數表示不添加用戶家目錄,-s參數表示指定shell類型

[root@nginx-1.8.0 ~]#useradd www -M -s /sbin/nologin
[root@nginx-1.8.0 ~]##vim auto/cc/gcc
#將這句注釋掉 取消Debug編譯模式 大概在179行
#CFLAGS="$CFLAGS -g"

#我們再配置下nginx編譯參數
[root@nginx-1.8.0 ~]# ./configure --prefix=/opt/nginx --user=www --group=www --with-http_stub_status_module --with-http_ssl_module
[root@nginx-1.8.0 ~]#make
[root@nginx-1.8.0 ~]#make install clean

2)配置nginx
[root@nginx-1.8.0 ~]# cd /opt/nginx/conf
注意,把默認的nginx.conf文件中的server區域配置注釋掉,設置vhosts虛擬主機的配置,如下:
[root@nginx-1.8.0 conf]# vim nginx.conf
user  www;
worker_processes  8;
   
events {
    worker_connections  65535;
}
   
http {
    include       mime.types;
    default_type  application/octet-stream;
    charset utf-8;
  
    log_format  main  '$http_x_forwarded_for $remote_addr $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_cookie" $host $request_time';
    sendfile       on;
    tcp_nopush     on;
    tcp_nodelay    on;
    keepalive_timeout  65;
  
  
    fastcgi_connect_timeout 3000;
    fastcgi_send_timeout 3000;
    fastcgi_read_timeout 3000;
    fastcgi_buffer_size 256k;
    fastcgi_buffers 8 256k;
    fastcgi_busy_buffers_size 256k;
    fastcgi_temp_file_write_size 256k;
    fastcgi_intercept_errors on;
   
      
    client_header_timeout 600s;
    client_body_timeout 600s;
   
    client_max_body_size 100m;            
    client_body_buffer_size 256k;          
   
    gzip  on;
    gzip_min_length  1k;
    gzip_buffers     4 16k;
    gzip_http_version 1.1;
    gzip_comp_level 9;
    gzip_types       text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php;
    gzip_vary on;
   
  
    include vhosts/*.conf;
}

[root@nginx-1.8.0 conf]# ulimit -n 65535
[root@nginx-1.8.0 conf]# mkdir vhosts
[root@nginx-1.8.0 conf]# cd vhosts

[root@nginx-1.8.0 conf]# vim 8080.conf
server {
    listen 8080;
    server_name localhost;
    index index.html index.php index.htm;
  
    access_log  /usr/local/nginx/logs/8080-access.log main;
    error_log  /usr/local/nginx/logs/8080-error.log;
 
location ~ / {
    root /var/www/html/8080;
    index index.html index.php index.htm;
}
}

[root@nginx-1.8.0 conf]# vim 8090.conf
server {
    listen 8090;
    server_name localhost;
    index index.html index.php index.htm;
  
    access_log  /usr/local/nginx/logs/8090-access.log main;
    error_log  /usr/local/nginx/logs/8090-error.log;
 
location ~ / {
    root /var/www/html/8090;        #針對上面匹配ios的path代理,要保證站點目錄/var/www/html/8080下有ios目錄存在
    index index.html index.php index.htm;
}
}

[root@nginx-1.8.0 conf]# vim 80.conf
server {
   listen 80;
   server_name localhost;
   index index.html index.php index.htm;
  
   access_log  /usr/local/nginx/logs/80-access.log main;
   error_log  /usr/local/nginx/logs/80-error.log;
 
location ~ / {
   root /var/www/html;
   index index.html index.php index.htm;
}
}

啟動nginx
[root@nginx-1.8.0 vhosts]# /opt/nginx/sbin/nginx -t 
nginx: the configuration file /opt/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /opt/nginx/conf/nginx.conf test is successful

[root@host-192-168-1-102 vhosts]# /opt/nginx/sbin/nginx 

==========================================================================================
后端機:C機器上的操作記錄

1)編譯安裝nginx
[root@C ~]# yum install -y pcre* openssl* gcc gcc+
[root@C ~]# cd /opt/src
[root@C ~]# wget http://nginx.org/download/nginx-1.8.0.tar.gz
[root@C ~]# tar -zxvf nginx-1.8.0.tar.gz
[root@C ~]# cd nginx-1.8.0
#添加www用戶,其中-M參數表示不添加用戶家目錄,-s參數表示指定shell類型

[root@nginx-1.8.0 ~]#useradd www -M -s /sbin/nologin
[root@nginx-1.8.0 ~]##vim auto/cc/gcc
#將這句注釋掉 取消Debug編譯模式 大概在179行
#CFLAGS="$CFLAGS -g"

#我們再配置下nginx編譯參數
[root@nginx-1.8.0 ~]# ./configure --prefix=/opt/nginx --user=www --group=www --with-http_stub_status_module --with-http_ssl_module
[root@nginx-1.8.0 ~]#make
[root@nginx-1.8.0 ~]#make install clean

2)配置nginx
[root@nginx-1.8.0 ~]# cd /opt/nginx/conf
注意,把默認的nginx.conf文件中的server區域配置注釋掉,設置vhosts虛擬主機的配置,如下:
[root@nginx-1.8.0 conf]# vim nginx.conf

user  www;
worker_processes  8;
   
events {
    worker_connections  65535;
}
   
http {
    include       mime.types;
    default_type  application/octet-stream;
    charset utf-8;
  
    log_format  main  '$http_x_forwarded_for $remote_addr $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_cookie" $host $request_time';
    sendfile       on;
    tcp_nopush     on;
    tcp_nodelay    on;
    keepalive_timeout  65;
  
  
    fastcgi_connect_timeout 3000;
    fastcgi_send_timeout 3000;
    fastcgi_read_timeout 3000;
    fastcgi_buffer_size 256k;
    fastcgi_buffers 8 256k;
    fastcgi_busy_buffers_size 256k;
    fastcgi_temp_file_write_size 256k;
    fastcgi_intercept_errors on;
   
      
    client_header_timeout 600s;
    client_body_timeout 600s;
   
    client_max_body_size 100m;            
    client_body_buffer_size 256k;          
   
    gzip  on;
    gzip_min_length  1k;
    gzip_buffers     4 16k;
    gzip_http_version 1.1;
    gzip_comp_level 9;
    gzip_types       text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php;
    gzip_vary on;
   
  
    include vhosts/*.conf;
}

[root@nginx-1.8.0 conf]# vim 80.conf
server {
    listen 80;
    server_name localhost;
    index index.html index.php index.htm;
  
    access_log  /usr/local/nginx/logs/80-access.log main;
    error_log  /usr/local/nginx/logs/80-error.log;
 
location ~ / {
    root /var/www/html/;
    index index.html index.php index.htm;
}
}

啟動nginx
[root@nginx-1.8.0 vhosts]# /opt/nginx/sbin/nginx -t 
nginx: the configuration file /opt/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /opt/nginx/conf/nginx.conf test is successful

[root@host-192-168-1-102 vhosts]# /opt/nginx/sbin/nginx 


到此,上面需求中的nginx反向代理和負載均衡就已經配置完成了!
訪問http://103.110.86.8:8080的結果顯示的就是B機器,即http://192.168.1.102:8080的結果
訪問http://103.110.86.8:8088的結果顯示的就是C機器,即http://192.168.1.108:8088的結果
訪問http://103.110.86.8:8090/ios的結果顯示的就是B機器,即http://192.168.1.102:8090/ios/的結果

訪問http://103.110.86.8的請求就會被負載給到后端兩台機器http://192.168.1.102和http://192.168.1.103

可以在103.110.86.8本機可以使用curl和telnet測試到目標機器是否通順~
[root@nginx-1.8.0 vhosts]# curl http://192.168.1.102:8080
[root@nginx-1.8.0 vhosts]# telnet 192.168.1.102 8080

                                                                                                                                                      
說明一下:上面的nginx反向代理的需求,除了nginx反代配置之外,也可以使用iptables的nat轉發實現。
比如:訪問A機器的8080端口,反向代理到B機器的80端口;iptables的nat轉發規則設置如下:

[root@opd ~]# iptables -t nat -A PREROUTING -p tcp -m tcp --dport 8080 -j DNAT --to-destination 192.168.1.102:80 
[root@opd ~]# iptables -t nat -A POSTROUTING -d 192.168.1.102 -p tcp -m tcp --sport 80 -j SNAT --to-source 192.168.1.8
[root@opd ~]# iptables -t filter -A INPUT -p tcp -m state --state NEW -m tcp --dport 8080 -j ACCEPT

[root@opd ~]# service iptables save

**************************************
需要注意的是:
要打開A機器的ip轉發功能:
[root@opd ~]# echo 1 > /proc/sys/net/ipv4/ip_forward
然后后端機器B的route路由最好也設置成192.168.1.8
**************************************

這樣,訪問http://103.110.86.8:8080的結果就是http://192.168.1.102的結果

                                                                                                                                                   
nginx反向代理一例:訪問 http://testwx3.wangshibo.com/apiwx3   反向代理到    https://testwww.wangshibo.com

[root@dev-new-test vhosts]# cat testwx3.wangshibo.com.conf
server {
        listen       80;
 
        server_name  testwx3.wangshibo.com;
        root  /Data/app/xqsj_wx3/dist;
        index index.html;
 
    location /apiwx3/ {
        proxy_pass https://testwww.wangshibo.com/;
    }

如上配置后:
訪問 http://testwx3.wangshibo.com/apiwx3  自動跳轉到  http://testwx3.wangshibo.com/apiwx3/
訪問 http://testwx3.wangshibo.com/apiwx3/$1 的內容和 https://testwww.wangshibo.com/$1 內容一致
比如:
訪問 http://testwx3.wangshibo.com/apiwx3/xqsj.php?r=HouseGroup/create  顯示的內容既是  http://testwww.wangshibo.com/xqsj.php?r=HouseGroup/create 的內容

如果將上面的代理配置改為:

location /apiwx3 {
    proxy_pass https://testwww.wangshibo.com;
}
 
或者
    location /apiwx3/ {
    proxy_pass https://testwww.wangshibo.com/;
}

那么只能實現:訪問 http://testwx3.wangshibo.com/apiwx3 的結果和 https://testwww.wangshibo.com 一致
不能實現:訪問http://testwx3.wangshibo.com/apiwx3/$1的內容和https://testwww.wangshibo.com/$1內容一致


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM