Nginx
Nginx 查詢字元串重寫
我有如下配置,但我收到 500 錯誤。這個錯誤可能在哪裡?
upstream masterservers {server 192.168.1.1:8000;} upstream slaveservers {server 192.168.1.2:8001;} map $request_uri $redirect_to { "target=master" masterservers; "target=slave" slaveservers; } server { listen 80; server_name 192.168.1.10; location / { proxy_pass http://$redirect_to; } }
當我如下呼叫 URL 時,出現以下錯誤。
http://192.168.1.10/app/index.html?target=master
http://192.168.1.10/app/index.html?target=slave
Nginx 日誌:
*2 invalid URL prefix in "http://", client: 192.168.1.11, server: 192.168.1.10, request: "GET /favicon.ico HTTP/1.1", host: "192.168.1.10", referrer: "http://192.168.1.10/app/index.html?target=master"
您正在將您的
$request_uri
(等於/app/index.html?target=master
您的範例中的 to)target=master
與target=slave
字元串進行比較。沒有匹配,因此$redirect_to
變數變為空字元串。如果要檢查是否$request_uri
包含 atarget=master
或target=slave
子字元串,可以在map
塊內使用正則表達式模式:map $request_uri $redirect_to { "~target=master" masterservers; "~target=slave" slaveservers; }
或更好地檢查
$arg_target
變數值:map $arg_target $redirect_to { master masterservers; slave slaveservers; }
當請求中沒有指定查詢參數(或其值無效)時,還可以考慮使用一些
default
值:target
map $arg_target $redirect_to { master masterservers; slave slaveservers; default masterservers; }
最後一個可以簡化為
map $arg_target $redirect_to { slave slaveservers; default masterservers; }
或進行一些初步檢查,例如
map $arg_target $redirect_to { master masterservers; slave slaveservers; } server { listen 80; server_name 192.168.1.10; if ($redirect_to = '') { return 501; # HTTP 501 Not Implemented } location / { proxy_pass http://$redirect_to; } }
更新
如果我正確理解您的附加問題 - 如何從與主 HTML 文件相同的上游載入所有資產 -如果使用兩個鍊式塊不存在查詢參數,您可以嘗試從 HTTP
Referer
標頭值獲取上游名稱(這裡是正則表達式真的到位):target``map
map $arg_target $redirect_to { master masterservers; slave slaveservers; default $by_referer; } map $http_referer $by_referer { "~target=master" masterservers; "~target=slave" slaveservers; } server { ... }