1. 程式人生 > 實用技巧 >nginx-location配置塊

nginx-location配置塊

location 配置塊

其中 location 用於匹配請求的 URI。

URI 表示的是訪問路徑,除域名和協議以外的內容,比如說我訪問了https://www.shiyanlou.com/louplus/linux,https:// 是協議,www.shiyanlou.com 是域名,/louplus/linux 是 URI。

location 匹配的方式有多種:

  • 精準匹配

  • 忽略大小寫的正則匹配

  • 大小寫敏感的正則匹配

  • 前半部分匹配

其語法如下:

location [ = | ~ | ~* | ^~ ] pattern {
#    ......
#    ......
}

其中各個符號的含義:

  • =:用於精準匹配,想請求的 URI 與 pattern 表示式完全匹配的時候才會執行 location 中的操作

  • ~:用於區分大小寫的正則匹配;

  • ~*:用於不區分大小寫的正則匹配;

  • ^~:用於匹配 URI 的前半部分;

我們以這樣的例項來進一步理解:

# 當訪問 www.xxx.com 時,請求訪問的是 /,所以將與配置 A 匹配;
location = / {
    # [ 配置 A ]
}
# 當訪問 www.xxx.com/test.html 時,請求將與配置 B 匹配;
location / {
    # [ 配置 B ]
}
# 當訪問 www.xxx.com/documents/document.html 時,請求將匹配配置 C
location /documents/ {
    # [ 配置 C ]
}
# 當訪問 www.xxx.com/images/1.gif 請求將匹配配置 D;
location ^~ /images/ {
    # [ 配置 D ]
}
# 當訪問 www.xxx.com/docs/1.jpg 請求將匹配配置 E。
location ~* \.(gif|jpg|jpeg)$ {
    # [ 配置 E ]
}

當一個 URI 能夠同時配被多 location 匹配的時候,則按順序被第一個 location 所匹配。

在 location 中處理請求的方式有很多,如上文中的 try_files $uri $uri/ =404;,它是一種特別常用的寫法。

我們來分析一下 try_files $uri $uri/ =404;。這裡假設我定義的 root 為/usr/share/nginx/html/,訪問的 URI 是 /hello/shiyanlou。

# 虛擬主機的配置
server {
    # 偵聽 80 埠,分別配置了 IPv4 和 IPv6
    listen 80 default_server;
    listen[::]:80 default_server ipv6only=on;

    # 定義伺服器的預設網站根目錄位置
    root /usr/share/nginx/html;

    # 定義主頁的檔名
    index index.html index.htm;

    # 定義虛擬伺服器的名稱
    server_name localhost;
    
    # location 塊
    location / {
        try_files $uri $uri/ =404;
    }
}
  • 第一步:當 URI 被匹配後,會先查詢/usr/share/nginx/html//hello/shiyanlou 這個檔案是否存在,如果存在則返回,不存在進入下一步。

  • 第二步:查詢 /usr/share/nginx/html//hello/shiyanlou/ 目錄是否存在,如果存在,按 index 指定的檔名進行查詢,比如 index.html,如果存在則返回,不存在就進入下一步。

  • 第三步:返回 404 Not Found。