簡體   English   中英

NGINX - 正則表達式到locations.conf 不起作用

[英]NGINX - Regex into locations.conf doesn't work

我的 nginx 代理配置有問題。 我只是嘗試使用正則表達式在這里定義: https : //underthehood.meltwater.com/blog/2017/12/12/lightweight-tests-for-your-nginx-api-gateway/

但沒有任何作用。 如果路徑中有任何正則表達式,我的服務器將無法啟動。 我試過:

location ~ ^/tesla/(?<id>.*)$ {
 proxy_pass http://localhost:8081/;
 proxy_set_header        Host                  $host;
} 

或者

location ~ ^/tesla/test/ {
 proxy_pass http://localhost:8081/;
 proxy_set_header        Host                  $host;
}

或者

location ~* ^/tesla/test/ {
 proxy_pass http://localhost:8081/;
 proxy_set_header        Host                  $host;
}

沒有任何作用。 我的最終目標是從 url 中提取一個值並執行以下操作:

location ~* ^/(<version>.*)/test/ {
 proxy_pass http://localhost:8081/;
 proxy_set_header        Host                  $host;
 proxy_set_header        X-Forwarded-Prefix    $version;
}

更新(已解決)

感謝理查德,我終於成功了。 這是完整的代碼:

location ~* ^/api/(?<version>.*)/(?<service>.*)(/.*/.*)$   {
  proxy_pass  http://$service.localnetwork:8080$3;
  proxy_set_header        Host                  $host;
  proxy_set_header        X-Real-IP             $remote_addr;
  proxy_set_header        X-Forwarded-For       $proxy_add_x_forwarded_for;
  proxy_set_header        X-Forwarded-Prefix    /api/$version/$service;
  proxy_set_header        msvc_name    $service;
  proxy_set_header        msvc_version    $version;
}

您不能在正則表達式location塊中使用帶有靜態 URI 的proxy_pass ,它會引發錯誤 - 請參閱您的 Nginx 錯誤日志。 有關詳細信息,請參閱此文檔

但是,您可以通過將變量附加到proxy_pass語句來構造要向上游發送的 URI。 在您的情況下,您可以在同一正則表達式中捕獲 URI 的其余部分。

例如:

location ~* ^/([^/]+)/test(/.*)$ {
    proxy_pass http://localhost:8081$2;
    proxy_set_header  Host                $host;
    proxy_set_header  X-Forwarded-Prefix  $1;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM