Nginx 可以正確重寫其中一個,但無法正確重寫另一個

Nginx 可以正確重寫其中一個,但無法正確重寫另一個

基本上,我嘗試使用該proxy_pass指令來呼叫遠端 API。

到目前為止,這就是我得到的:

server {
  location /a {
    proxy_pass https://a.com;
    rewrite ^/a(.*)$ $1 break; # no trailing slash, defined in application code
  }
  location /b {
    proxy_pass https://b.com;
    rewrite ^/b(.*)$ $1 break; # no trailing slash, defined in application code
  }
  location / {
    # Rest of configuration
  }
}

我堅持這樣一個事實:location /a工作正常,但location /b由於某種原因卻不能(HTTP/404)。


location /b我嘗試用​​這種方式使用尾部斜杠

location /b/ {
  proxy_pass https://b.com/;
  rewrite ^/b/(.*)$ $1 break;
}

但這也行不通。

非常歡迎任何幫助。

答案1

我找到了我的特定問題的答案。

兩個 API 伺服器的設定方式不同,我必須稍微調整一下 nginx 設定。

  • 伺服器b.com需要一個proxy_set_header Host $host指令和不需要rewrite指令
  • 伺服器a.com需要該rewrite指令,但不需要proxy_set_header Host $host

這給我留下了以下(對我有用)配置:

server {
    location /a {
        proxy_pass  https://a.com;
        rewrite ^/a(.*)$ $1 break;
    }
    location /b {
        proxy_set_header Host $host;
        proxy_pass  https://b.com;
    }
}

相關內容