2017-09-06 75 views
0

我使用nginx作爲反向代理,我有一個服務器作爲API和Websocket服務器。爲了使用WebScoket我需要指定一些標題:Nginx位置的API請求和一個位置的所有websockets請求

proxy_set_header Upgrade $http_upgrade; 
proxy_set_header Connection "upgrade"; 

但是,我有一些錯誤的API請求,以解決它,我必須使用:

proxy_set_header Connection keep-alive; 

但是,上面的行打破了websocket連接。所以,我可以用幾個位置修正:

location/{ 
     proxy_pass http://0.0.0.0:5000; 
     proxy_http_version 1.1;   
     proxy_set_header Connection keep-alive; 
     proxy_set_header Host $host;   
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
} 

location /someWebSocketUrl{ 
     proxy_pass http://0.0.0.0:5000; 
     proxy_http_version 1.1; 
     proxy_set_header Upgrade $http_upgrade; 
     proxy_set_header Connection "upgrade"; 
} 

location /anotherWebSocketUrl{ 
     proxy_pass http://0.0.0.0:5000; 
     proxy_http_version 1.1; 
     proxy_set_header Upgrade $http_upgrade; 
     proxy_set_header Connection "upgrade"; 
} 

location /oneMoreWebSocketUrl{ 
     proxy_pass http://0.0.0.0:5000; 
     proxy_http_version 1.1; 
     proxy_set_header Upgrade $http_upgrade; 
     proxy_set_header Connection "upgrade"; 
} 

我不喜歡,我必須對每一個網絡插座網址單獨的位置。有可能簡化它嗎?喜歡的東西:

location allWebSocketUrls_or_wss:// { 
    ... 
} 

回答

0

只需使用的所有語句:

location /websocketUrl { 
    ... 
} 

對於任何位置,其開始爲 「/ websocketUrl *」。或使用正則表達式:

location ~ /(some|another|oneMore)?websocketUrl[1-3]*$ { 
    ... 
} 

如果您想要確切的URL。或者更簡單:

location ~ /.*websocketUrl.*$ { 
    ... 
} 

它被用於任何「websocketUrl」。我認爲,它更好地使用特殊目錄所有插座,但這樣一來也可以工作/

但是,如果你把所有相同的選項,嘗試禁用頭:

location =/{ 
     proxy_pass http://0.0.0.0:5000; 
     proxy_http_version 1.1; 
     proxy_set_header Connection keep-alive; 
     proxy_set_header Upgrade $http_upgrade; 
     proxy_set_header Connection "upgrade"; 
} 

location/{ 
     proxy_pass http://0.0.0.0:5000; 
     proxy_http_version 1.1;   
     proxy_set_header Connection ""; # <--- this will disable header 
     proxy_set_header Host $host;   
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
} 
+0

名字'websocketUrl1-3'只是例如...對不起,我不得不提到它。 – user348173

+0

@ user348173,好,更新後 – bukkojot