Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 伺服器技術 >> 關於伺服器

Nginx Location 指令完整語法與實戰範例

編輯:關於伺服器

核心語法

location [= | ~ | ~* | ^~] /uri/ { ... }

修飾符優先級與行為

修飾符說明優先級
=精確匹配,匹配成功立即停止搜尋最高
^~前綴匹配,匹配成功不再測試正則高
~區分大小寫正則匹配中
~*不區分大小寫正則匹配中
!~ / !~*不匹配正則(區分/不區分大小寫)中
無修飾符前綴匹配(字串比對)低

匹配順序邏輯

  1. 精確匹配 =
  2. 前綴匹配 ^~ 與無修飾符(最長前綴優先)
  3. 正則匹配 ~ ~*(配置檔順序優先)
  4. 預設 location /

實戰範例解析

範例 1:精確匹配首頁

location = / {
    # 僅匹配 / 請求
    [ configuration ]
}

範例 2:靜態資源快取與防盜鏈

# 圖片快取 1 小時
location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ {
    if (-f $request_filename) {
        expires 1h;
        break;
    }
}

# 防盜鏈:僅允許指定域名引用圖片
location ~* \.(gif|jpg|swf)$ {
    valid_referers none blocked start.example.com sta.example.com;
    if ($invalid_referer) {
        rewrite ^/ https://$host/logo.png;
    }
}

範例 3:目錄存取控制

# 禁止存取特定副檔名
location ~* \.(txt|doc)$ {
    root /data/www/wwwroot/test;
    deny all;
}

# 優先匹配 /images/ 目錄,不再進入正則判斷
location ^~ /images/ {
    # 圖片處理邏輯
}

範例 4:完整虛擬主機配置片段

server {
    listen 80;
    server_name example.com;

    location = / { ... }           # 精確首頁
    location / { ... }             # 預設 fallback
    location ^~ /images/ { ... }   # 靜態目錄優先
    location ~* \.(php|php5)$ {    # PHP 處理
        fastcgi_pass 127.0.0.1:9000;
        include fastcgi_params;
    }
}

常用內建變數速查

  • $request_filename:請求檔案完整路徑
  • $remote_addr:客戶端 IP
  • $host:請求 Host 標頭
  • $uri:不帶參數的請求 URI
  • $args / $query_string:查詢字串

避坑提醒

  • 正則前需加 ~ 或 ~*,否則視為字串前綴匹配
  • ^~ 僅適用於字串前綴,不可搭配正則
  • 巢狀 location 繼承父層設定,但可被覆寫
  • 大量正則影響效能,靜態路徑優先用 ^~
Copyright © Windows教程網 All Rights Reserved