nginx 配置日記
1. root與alias 的差別
一般nginx映射資源檔案大多數都是這樣寫
# 被通路的資源目錄為/nice/ooxx/路徑下的檔案
# 寫法 1
server {
location ^~ /ooxx/ {
root /nice/;
index index.html index.hml index;
}
}
# 寫法 2
server {
location ^~ /xxxoodd/ {
alias /nice/ooxx/;
index index.html index.hml index;
}
}
這兩種寫法都是為了通路/nice/ooxx/路徑下的資源檔案,但是卻有所差別
- 寫法1的比對規則是 root + location的到請求資源的路徑,
- alias 之間将請求xxxoodd的路徑改名為/nice/ooxx/ + 請求url去除location部分的内容(如請求的路徑是/xxxoodd/nice.html那麼真實通路的路徑是/nice/ooxx/nice.html。location的内容被截斷,并将後面的内容映射到alias路徑的後面)
- alias 後面跟随的路徑必以“/”結尾,否則無法請求到對應的路徑
2. nginx 映射檔案路徑
寫法如下
server {
listen 80;
charset utf-8;
location /nice/ {
root /data/nice/imgs;
autoindex on; # 顯示目錄
autoindex_excat_size on; # 顯示檔案大小
autoindex_locationtime on; # 顯示檔案的修改時間
}
}
3. nginx中的server_name
nginx配置中的server_name用于區分通過不同域名發來的請求通路不同的服務。可能比較繞舉個例子
假設你有個IP:10.143.110.110有兩個域名都映射到了這個IP上分别是www.nice1.com和www.nice2.com
如果你想同請求的域名來去分,當請求是通過www.nice1.com通路時,将請求轉發到服務A(www.a.com),如果是通過www.nice2.com域名通路的将請求轉發到服務B(www.b.com)該怎麼做?
這時server_name就派上用場了将配置改成如下:
server {
listen 80;
charset utf-8;
server_name www.nice1.com;
location / {
proxy www.a.com;
}
}
server {
listen 80;
server_name www.nice2.com;
location / {
proxy www.b.com;
}
}
這樣就可以通過域名區分請求了
注意: 通過server_name設定後隻能通過server_name設定的域名來請求服務,其他的域名的請求是沒法請求到的。
如:通過IP去請求curl 10.143.110.110。傳回404。
4. nginx的正則
符号 | 描述 |
---|---|
\ | 轉義字元将特殊字元如要轉義正則中的?字元,在正則中應這樣寫 \\\\? |
^ | 比對字元串的開始位置,如比對以/vip/nice開頭的字元串,正則應這樣寫 ^/vip/nice.* |
$ | 比對字元串的結束位置,如比對以/vip/nice結尾的字元串,正則應這樣寫 .*/vip/nice$ |
. | 比對出換行符’\n’以外的所有單個字元 |
* | 比對前面字元的0次或多次 |
+ | 比對前面字元的1次或多次 |
? | 比對前面字元的0次或1多次 |
(pattern) | 括号内比對的内容,取值時,通常$1、$2、$3… 數字為取第幾個括号比對到的内容 |
5. rewrite的使用
rewrite是本質是實作請求的重定向(請區分請求轉發、重定向的差別)
使用文法:rewrite <regex> <replacement[flag]>;
應用位置:server、location、if
示例:
# 将指定url字首的請求轉發到其他的伺服器上
server {
listen 80;
charset utf-8;
server_name www.nice.com;
location /web/s/ {
# $1 表示取(.*)比對到的内容, 如果後面還有(...)則為$2、$3 ...
rewrite ^/(.*)$ www.baidu.com/$1 permanent;
}
}
rewrite 最後的flag參數:
标記符号 | 說明 |
---|---|
last | 本條規則比對完成後繼續向下比對新的location URI規則 |
break | 本條規則比對完成後終止,不在比對任何規則 |
redirect | 傳回302臨時重定向 |
permanent | 傳回301永久重定向 |