nginx反向代理配置

nginx配置文件位置/usr/local/nginx/conf/nginx.confhtml

配置文件修改:
# cd /usr/local/nginx/conf
# vim nginx.confnginx

server {
	listen       80;
	server_name  localhost;

	#charset koi8-r;

	#access_log  logs/host.access.log  main;

	location / {
		root   html;
		index  index.html index.htm;
	}
}

 改成:正則表達式

server {
	listen       80;
	server_name  nginx的ip地址;

	#charset koi8-r;

	#access_log  logs/host.access.log  main;

	location / {
		root   html;
		proxy_pass tomcat的ip地址;
		index  index.html index.htm;
	}
}

# /usr/local/nginx/sbin/nginx -s reloadvim

配置另外一個虛擬主機:tomcat

server {
	listen       9001;
	server_name  nginx的ip地址;

	location ~ /edu/ {
		proxy_pass 	tomcat1的ip地址:端口1;
	}
	location ~ /vod/ {
		proxy_pass 	tomcat2的ip地址:端口2;
	}
}

配置文件包含三部份內容
(1)全局塊:配置服務器總體運行的配置指令 好比 worker_processes  1;處理併發數的配置,值越大處理的併發量越大
(2)events 塊:影響 Nginx 服務器與用戶的網絡鏈接 好比 worker_connections  1024; 支持的最大鏈接數爲 1024 
(3)http 塊 還包含兩部分: http 全局塊 server 塊服務器

當咱們經過hosts文件指定IP與域名的對應關係(如:10.10.124.120   www.test.com)以後,對域名的訪問會映射成對應的IP,這個ip就是nginx的公網IP 。
請求頭攜帶了Host,所以不一樣的域名會經過請求頭中的HOST字段,由此nginx一定會拿它作uri匹配工做,匹配到特定的server塊,轉發到對應的應用服務器中去。網絡

server_name與host匹配優先級以下:
一、徹底匹配
二、通配符在前的,如*.test.com
三、在後的,如www.test.*
四、正則匹配,如~^\.www\.test\.com$
若是都不匹配
一、優先選擇listen配置項後有default或default_server的
二、找到匹配listen端口的第一個server塊併發

location區段
經過指定模式來與客戶端請求的URI相匹配,基本語法以下:location [=|~|~*|^~|@] pattern{……}
一、沒有修飾符 表示:必須以指定模式開始
二、=表示:必須與指定的模式精確匹配
三、~ 表示:指定的正則表達式要區分大小寫
四、~* 表示:指定的正則表達式不區分大小寫
五、^~ 相似於無修飾符的行爲,也是以指定模式開始,不一樣的是,若是模式匹配,那麼就中止搜索其餘模式了。
六、@ :定義命名location區段,這些區段客戶段不能訪問,只能夠由內部產生的請求來訪問,如try_files或error_page等負載均衡

查找順序和優先級
1:帶有「=「的精確匹配優先
2:沒有修飾符的精確匹配
3:正則表達式按照他們在配置文件中定義的順序
4:帶有「^~」修飾符的,開頭匹配
5:帶有「~」 或「~*」 修飾符的,若是正則表達式與URI匹配
6:沒有修飾符的,若是指定字符串與URI開頭匹配code

root 、alias指令區別
alias是一個目錄別名的定義,root則是最上層目錄的定義。

Location區段匹配示例

location = / {
  # 只匹配 / 的查詢.
  [ configuration A ]
}
location / {
  # 匹配任何以 / 開始的查詢,可是正則表達式與一些較長的字符串將被首先匹配。
  [ configuration B ]
}
location ^~ /images/ {
  # 匹配任何以 /images/ 開始的查詢而且中止搜索,不檢查正則表達式。
  [ configuration C ]
}
location ~* \.(gif|jpg|jpeg)$ {
  # 匹配任何以gif, jpg, or jpeg結尾的文件,可是全部 /images/ 目錄的請求將在Configuration C中處
  理。
  [ configuration D ]
} 各
請求的處理以下例:
■/ → configuration A
■/documents/document.html → configuration B
■/images/1.gif → configuration C
■/documents/1.jpg → configuration D

負載均衡配置
分配策略:1. 輪詢  2. weight  3. ip_hash  4. fair

upstream myserver {
	ip_hash
	server tomcat1的ip地址:端口1;
	server tomcat2的ip地址:端口2;
}
server {
	listen       80;
	server_name  nginx的ip地址;
	
	location / {
		proxy_pass 	http://myserver;
		root   html;
		index  index.html index.htm;
	}
}
相關文章
相關標籤/搜索