天天看點

nginx之location規則詳解

1.nginx執行過程

nginx之location規則詳解

首先,浏覽器通路一個url;

然後,圖中虛拟主機比對過程。進入到對應的nginx配置的虛拟機主機(也就是/etc/nginx/conf.d/下面的哪個虛拟主機);

其次,圖中location比對。進入到對應的虛拟主機裡面的location進行比對,會分為比對到的path和未比對到的path。

2.location中root和alias指令(靜态檔案處理)

root指令:root後面路徑+location路徑進行查找(預設是安裝nginx時的html目錄,建議生産環境寫絕對路徑);

alias指令:隻在alias後面目錄查找html檔案

#vim smallboy.conf
    server {
        listen       80;
        server_name  www.smallboy.com;

       #通路路徑:http://www.smallboy.com/static/a.html
       location /static { #比對路徑/static 剩餘路徑/a.html
               root html/; # root聲明:會在html檔案夾下,查找/static/a.html
       }
       #通路路徑:http://www.smallboy.com/target/a.html
       location /target { #比對路徑/target 剩餘路徑/a.html
               alias html/static/; #alias聲明:在html/static目錄下面查找a.html
       }

    }
           

通路:http://www.smallboy.com/static/a.html

nginx之location規則詳解

通路:http://www.smallboy.com/target/a.html

nginx之location規則詳解

3.proxy_pass轉第三方

① 通路路徑:http://www.smallboy.com/nginx/enjoy/getInfo 命中路徑/nginx/enjoy path1= /nginx/enjoy,path2=/getInfo, proxy_pass http://192.168.211.165:8081 未關閉,傳遞path1+path2到後段ip+port

nginx之location規則詳解

② 通路路徑:http://www.smallboy.com/target/nginx/enjoy/getInfo 命中路徑/target path1=target,path2=/nginx/enjoy/getInfo proxy_pass http://192.168.211.165:8081/ 已關閉,傳遞path2到後端ip+port

nginx之location規則詳解

③ proxy_pass關閉不關閉隻是針對ip+port後面有沒有/而言的。

4.location比對優先級

精準比對規則:

nginx之location規則詳解

精準比對測試:

通路:http://www.smallboy.com/wanglei/a/b/c 傳回402

nginx之location規則詳解

普通比對規則:

nginx之location規則詳解

普通比對測試:

通路 http://www.smallboy.com/match/a/b/c 傳回碼414

nginx之location規則詳解

正則比對規則:

nginx之location規則詳解

正則比對測試:

通路http://www.smallboy.com/rex/a/b/c.htm 傳回碼為500

nginx之location規則詳解

server {
listen       80;
server_name  www.smallboy.com;

# 精準比對測試
# 第1、2條雖然滿足,但第三條是精準比對,出第三條結果 
# 測試路徑 /wanglei/a/b/c
location ~ /wanglei/* { #正規表達式比對上路徑
       return 400;
}
location /wanglei/a/b { #普通規則比對上
       return 401;
}
location = /wanglei/a/b/c { #命中,精準比對上
       return 402;
}

# 普通比對測試
# 第1、2條雖然比對,但第三條比對更長,出第三條結果
# 測試路徑 /match/a/b/c
location /match/a { #被比對,但不是最長
       return 412;
}
location /match/a/b { #被比對,但不是最長
       return 413;
}
location /match/a/b/c { #被比對,且最長
       return 414;
}


#正則比對覆寫普通比對測試
#正則比對會覆寫普通比對,但不會覆寫=和^~
location = /re/a.js { #通路/re/a.js,直接命中,不會被後面正則比對上
       return 420;
}
location ^~ /re/a/b { #通路/re/a/b,直接命中,不會被後面正則覆寫
       return 421;
}
location /re/a.htm { #通路/re/a.htm,會被後面正則覆寫
       return 422;
}
location ~ /re/(.*)\.(htm|js|css)$ { #覆寫/re/a.htm
       return 423;
}

#正則比對成功一條後,便不在走其他正則
#最長正則比對是第三個,但比對第一個後便不往下走
#測試路徑/rex/a/b/c.htm
location ~ /rex/.*\.(htm|js|css)$ { #比對上這個後,其他不比對
       return 500;
}
location ~ /rex/a/(.*)\.(htm|js|css)$ { #比對上第一個後,不往下進行
       return 501;
}
location ~ /rex/a/b/(.*)\.(htm|js|css)$ { #比對上第一個後,不往下進行
       return 502;
}