location匹配模式
模式 含義
location = /uri = 表示精確匹配,只有完全匹配上才能生效
location ^~ /uri ^~ 開頭對URL路徑進行前綴匹配,并且在正則之前。
location ~ pattern 開頭表示區(qū)分大小寫的正則匹配
location ~* pattern 開頭表示不區(qū)分大小寫的正則匹配
location /uri 不帶任何修飾符,也表示前綴匹配,但是在正則匹配之后
location / 通用匹配,任何未匹配到其它location的請求都會匹配到,相當于switch中的default
proxy_pass反向代理
##第一種(訪問IP轉(zhuǎn)發(fā)到IP+端口)
server {
listen 9003;
server_name 192.168.50.248;
index index.php index.html index.htm;
location / {
proxy_pass http://127.0.0.1:9002;
}
}
當訪問192.168.50.248:9003 的時候, 就會轉(zhuǎn)發(fā)到192.168.1.114的9002端口, 9002端口我配置的是PHPinfo(); 所以最終會顯示PHPinfo的信息.
##第二種(訪問域名轉(zhuǎn)發(fā)到IP+端口去)
server{
listen 80;
server_name www.test1.com;
index index.php index.html index.htm;
location /{
proxy_pass http://127.0.0.1;
}
}
訪問www.test1.com 轉(zhuǎn)發(fā)到192.168.50.248默認的nginx顯示的頁面, 同樣可以加上端口比如: http://127.0.0.1:9002; 就跳轉(zhuǎn)到PHPinfo頁面
##第三種(訪問IP轉(zhuǎn)發(fā)到域名)
server {
listen 9003;
server_name 192.168.50.248;
index index.php index.html index.htm;
location /{
proxy_pass http://www.rubbish.top;
}
}
##第四種(訪問域名轉(zhuǎn)發(fā)到域名)
server{
listen 80;
server_name www.test1.com;
index index.php index.html index.htm;
location /{
proxy_pass http://www.baidu.com;
}
}
訪問www.test1.top跳轉(zhuǎn)到百度.
proxy_pass的http反向代理
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
location /api {
proxy_pass http://192.168.5.250:8081;
proxy_connect_timeout 600;
proxy_read_timeout 600;
}
location /{
proxy_pass http://127.0.0.1:8008; #轉(zhuǎn)發(fā)請求
}
proxy_pass http://web_pools; 用于指定反向代理服務器的服務器池。
proxy_set_header Host $host; 作用web服務器上有多個站點時,用該參數(shù)header來區(qū)分反向代理哪個域名。比如下邊的代碼舉例。
proxy_set_header X-Forwarded-For $remote_addr; 作用是后端服務器上的程序獲取訪客真實IP,從該header頭獲取。部分程序需要該功能。
upstream負載均衡
upstream backend {
ip_hash;
server backend1.example.com;
server backend2.example.com;
server backend3.example.com down;
server backend4.example.com;
}
tcp流量轉(zhuǎn)發(fā)
stream {
upstream cloudsocket {
hash $remote_addr consistent;
# $binary_remote_addr;
server 192.168.107.150:3306 weight=5 max_fails=3 fail_timeout=30s;
}
server {
listen 3307;#數(shù)據(jù)庫服務器監(jiān)聽端口
proxy_connect_timeout 10s;
proxy_timeout 300s;#設置客戶端和代理服務之間的超時時間,如果5分鐘內(nèi)沒操作將自動斷開。
proxy_pass cloudsocket;
}
}