2017-09-15 47 views
0

我想讓NGINX的解析器自動更新DNS解析緩存,所以我正在轉換爲使用變量作爲proxy_pass值來實現這一點。但是,當我使用變量時,它會將所有請求都發送到請求的根端點,並切斷URL的其他路徑。這是我的配置:NGINX - 在proxy_pass中使用變量中斷路由

resolver 10.0.0.2 valid=10s; 

server { 
    listen 80; 
    server_name localhost; 

    location /api/test-service/ { 
     proxy_redirect  off; 

     proxy_set_header X-Real-IP  $remote_addr; 
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 

     # If these 2 lines are uncommented, 'http://example.com/api/test-service/test' goes to 'http://example.com/api/test-service/' 
     set $pass_url http://test-microservice.example.com:80/; 
     proxy_pass $pass_url; 

     # If this line is uncommented, things work as expected. 'http://example.com/api/test-service/test' goes to 'http://example.com/api/test-service/test' 
     # proxy_pass http://test-microservice.example.com:80/; 

    } 

這對我沒有任何意義,因爲硬編碼的URL和變量的值是相同的。有什麼我失蹤?

編輯:啊,所以我找到了問題。但我不完全確定如何處理它。由於這是一個反向代理,我需要proxy_pass從URI中刪除/api/test-service/,然後再將它傳遞給代理。所以..

此:

http://example.com/api/test-service/test 

是否應代理這樣:

http://test-microservice.example.com:80/test 

但是,相反的代理這樣:

http://test-microservice.example.com:80/api/test-service/test 

當我不使用變量,它沒有問題。但是變量增加了它。這只是固有地使用變量會做什麼?

回答

0

有你在文檔中錯過了一個小點

When variables are used in proxy_pass: 
location /name/ { 
    proxy_pass http://127.0.0.1$request_uri; 
} 
In this case, if URI is specified in the directive, it is passed to the server as is, replacing the original request URI. 

所以你的配置需要改變,以

set $pass_url http://test-microservice.example.com:80$request_uri; 
proxy_pass $pass_url;