![Nginx 對映指令不符合規則](https://rvso.com/image/697395/Nginx%20%E5%B0%8D%E6%98%A0%E6%8C%87%E4%BB%A4%E4%B8%8D%E7%AC%A6%E5%90%88%E8%A6%8F%E5%89%87.png)
我有這個 nginx 設定檔:
map $request_uri $new_uri {
default DEFAULT;
/shell http://shell.com;
/lol http://lol.com;
}
map $request_uri $ret_code {
default 301;
/shell 301;
/lol 302;
}
server {
listen 80;
server_name TestDomain.com www.TestDomain.com;
location / {
add_header X-request_uri $request_uri;
add_header X-new_uri $new_uri;
add_header X-return_code $ret_code;
if ($new_uri = "DEFAULT") {
return 301 https://ashfame.com$request_uri;
}
if ($ret_code = 301) {
return 301 $new_uri;
}
if ($ret_code = 302) {
return 302 $new_uri;
}
}
}
地圖指令根本不起作用,只是預設為預設定義的任何內容。
例如:
$ curl -I testdomain.com/lol
HTTP/1.1 301 Moved Permanently
Server: nginx/1.10.0 (Ubuntu)
Date: Sun, 22 Jan 2017 20:04:06 GMT
Content-Type: text/html
Content-Length: 194
Connection: keep-alive
Location: https://ashfame.com/lol
X-request_uri: /lol
X-new_uri: DEFAULT
X-return_code: 301
/lol
應該設定$new_uri
為http://lol.com
和$ret_code
as 302
,但是如果您查看X-
標頭,它只是採用映射中指定的預設值。
一週前,我得到了相同的 nginx 配置,從那時起沒有任何變化。我確實打開了 ubuntu 的自動安全性升級,但我認為 nginx 甚至沒有更新。跑步v1.10.0
。無法真正指出為什麼這會停止工作。
編輯:剛剛在不同的 VPS、相同的 nginx 版本上測試了相同的配置,它可以正常工作。我現在該如何解決這個問題?
答案1
我想通了這個問題。我為每個網域都有多個這樣的配置文件,並且由於映射是在 http 上下文中定義的,所以最後一個文件覆蓋了變數的值。我透過在每個設定檔中添加變數名稱後綴來修復它,以便變數是唯一的:
map $request_uri $new_uri_5 {
default DEFAULT;
/shell http://shell.com;
/lol http://lol.com;
}
map $request_uri $ret_code_5 {
default 301;
/shell 301;
/lol 302;
}
server {
listen 80;
server_name TestDomain.com www.TestDomain.com testdomain.com www.testdomain.com;
location / {
add_header X-request_uri $request_uri;
add_header X-new_uri $new_uri_5;
add_header X-return_code $ret_code_5;
if ($new_uri_5 = "DEFAULT") {
return 301 https://ashfame.com$request_uri;
}
if ($ret_code_5 = 301) {
return 301 $new_uri_5;
}
if ($ret_code_5 = 302) {
return 302 $new_uri_5;
}
}
}
5 是我係統中該特定域的 ID。
答案2
我在 Nginx 1.12.2 上遇到了同樣的問題——map 指令不匹配任何模式,甚至是最簡單和最瑣碎的模式,例如/
,並且始終使用預設值。
$uri
該問題是由映射中使用變數引起的。某些 Nginx 設定會$uri
透過新增前綴來隱含地修改其原始值/index.php
,這會導致模式不符。這種行為$uri
是設計使然,並且兩者之間存在確切區別$request_uri
和$uri
變數。
修復方法是取代 Nginx 配置中的 URI 變數:
map $uri $result_var {
# ...
}
具有以下內容:
map $request_uri $result_var {
# ...
}