使用嵌套位置正则expression式在指定位置添加代理标头

我正在尝试使用Nginx和Puma在我的Rails API上设置一个WebSocket端点。

我有(工作但丑陋)

下面的Nginxconfiguration工作正常 ,但我觉得我可以使用更聪明的东西,以避免重复@puma@puma_ws命名的位置:

 upstream puma { server unix:///path/to/socket.sock; } server { listen 80; server_name example.com; root /var/www/public; location / { try_files $uri/index.html $uri @puma; } location ~ ^/api/websocket { try_files $uri/index.html $uri @puma_ws; } location @puma { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://puma; } location @puma_ws { # These two lines are the only difference compared to @puma proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://puma; } } 

注意:我正在使用WS位置的正则expression式( ~ ^/api/websocket ),因为在我的实际使用情况中,我需要有多个WS端点。 我简化了这个post的简单性。

最初的想法

我的第一个想法是只有一个命名位置@puma ,这将有一个嵌套的位置与正则expression式,只会添加两个所需的proxy_set_header

这样,我将只有一个try_files与唯一@puma命名的位置,这将添加标题本身使用嵌套的location

然而,afaik不可能在指定位置嵌套location块。

你有更好的主意来添加这些基于对实际URI的testing的头?

谢谢!

根据理查德对原文的评论,我提出的最初的解决scheme并不是那么糟糕。

但是,因为我喜欢避免重复自己,所以我select了包含@puma@puma_ws之间的公共configuration部分的文件。

所以我最后得到了这样的结果:

/etc/nginx/puma_proxy.conf

 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; 

主机configuration文件

 upstream puma { server unix:///path/to/socket.sock; } server { listen 80; server_name example.com; root /var/www/public; location / { try_files $uri/index.html $uri @puma; } location ~ ^/api/websocket { try_files $uri/index.html $uri @puma_ws; } location @puma { include /etc/nginx/puma_proxy.conf proxy_pass http://puma; } location @puma_ws { include /etc/nginx/puma_proxy.conf proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_pass http://puma; } } 

张贴在这里,以防有人可能真的喜欢这种方式。

请告诉我,如果你有更好的方法来处理这种情况,我很乐意有你的select!