Nginx入門到實戰(4)常見問題

1、相同 server_name 多個虛擬主機優先級

#當出現虛擬主機域名相同的狀況,重啓nginx時,會出現警告⚠️處理,可是並不不會阻止nginx繼續使用

server {
    listen 80;
    server_name www.baidu.com
    ...
}

server {
    listen 80;
    server_name www.baidu.com
    ...
}

...

優先選擇最新讀取到的配置文件,當多個文件是經過include時,文件排序越靠前,越早被讀取

2、location 匹配優先級

=        #進行普通字符精確匹配,徹底匹配
 ^~       #進行普通字符匹配,當前表示前綴匹配
 ~\~*     #表示執行一個正則匹配()

#當程序使用精確匹配時,一但匹配成功,將中止其餘匹配
#當正則匹配成功時,會繼續接下來的匹配,尋找是否還有更精準的匹配

3、try_files的使用

按順序檢查文件是否存在php

location / {
    try_files $uri $uri/ /index.php;
}

#先查找$uri下是否有文件存在,若存在直接返回給用戶
#若$url下沒有文件存在,再次訪問$uri/的路徑是否有文件存在
#仍是沒有文件存在,交給index.php處理

例:
location / {
    root /test/index.html
    try_files $uri @test
}

location @test {
    proxy_pass http://127.0.0.1:9090;
}

#訪問 / 時,查看 /test/index.html 文件是否存在
#若不存在,讓9090端口的程序去處理這個請求

4、alias和root的區別

location /request_path/image/ {
    root /local_path/image/;
}

#當咱們訪問 http://xxx.com/request_path/image/cat.png時
#將訪問 http://xxx.com/request_path/image/local_path/image/cat.png 下的文件

location /request_path/image/ {
    alias /local_path/image/;
}

#當咱們訪問 http://xxx.com/request_path/image/cat.png時
#將訪問 http://xxx.com/local_path/image/cat.png 下的文件

4、若是用戶真實IP

當一個請求經過多個代理服務器時,用戶的IP將會被代理服務器IP覆蓋html

#在第一個代理服務器中設置
    set x_real_ip=$remote_addr
#最後一個代理服務器中獲取
    $x_real_ip=IP1

5、Nginx 常見錯誤碼

413 Request Entity Too Large    #上傳文件過大,設置 client_max_body_size
503 bad gateway                 #後端服務無響應
504 Gateway Time-out            #後端服務執行超時
相關文章
相關標籤/搜索