nginx - 在nginx中根据request_method设置proxy_pass
问题描述
我有两个应用程序和一个 nginx 服务器。我想将 nginx 上的所有 GET 请求代理到在http://127.0.0.1:9101/上运行的一个应用程序,并将所有其他请求方法代理到http://10.41.115.241:8000/
我尝试了几个选项,但没有一个有效我尝试使用 limit_exempt
location /api/v1/executions {
error_page 502 = @apiError;
rewrite ^/api/(.*) /$1 break;
proxy_pass http://127.0.0.1:9101/;
limit_except PUT POST DELETE {
proxy_pass http://10.41.115.241:8000/;
}
proxy_read_timeout 90;
proxy_connect_timeout 90;
proxy_redirect off;
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 Connection '';
chunked_transfer_encoding off;
proxy_buffering off;
proxy_cache off;
#proxy_set_header Host $host;
}
我也试过如果条件
location /api/v1/executions {
error_page 502 = @apiError;
rewrite ^/api/(.*) /$1 break;
proxy_pass http://10.41.115.241:8000/;
if ($request_method = GET) {
proxy_pass http://127.0.0.1:9101/;
}
proxy_read_timeout 90;
proxy_connect_timeout 90;
proxy_redirect off;
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 Connection '';
chunked_transfer_encoding off;
proxy_buffering off;
proxy_cache off;
#proxy_set_header Host $host;
}
但在这两种方式我都得到了这个错误
"proxy_pass" cannot have URI part in location given by regular expression, or inside named location, or inside "if" statement, or inside "limit_except" block in /path/to/config
解决方案
始终尝试在 NGINX 中使用map
而不是if
用于条件逻辑。除非绝对不可能map
.. 在您的特定情况下,这很容易。
根据请求方法创建一个变量,该变量$backend
将保存您想要的值:proxy_pass
http {
map $request_method $backend {
default http://10.41.115.241:8000/;
GET http://127.0.0.1:9101/;
}
...
}
然后在你的配置中使用它:
location /api/v1/executions {
error_page 502 = @apiError;
rewrite ^/api/(.*) /$1 break;
proxy_pass $backend;
proxy_read_timeout 90;
proxy_connect_timeout 90;
proxy_redirect off;
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 Connection '';
chunked_transfer_encoding off;
proxy_buffering off;
proxy_cache off;
#proxy_set_header Host $host;
}
推荐阅读
- c# - EF Core 2 提供程序特定 HasDefaultValueSql
- c - 当我从项目中打开任何文件时,CodeBlocks 崩溃?
- python - 如何将解析的参数转换为可以在 if 语句中使用的变量?
- python - 计算概率密度均值python
- c# - Perforce API (P4API.NET): P4Exception: Too many try to get lock p4tickets.txt.lck
- python - 如何为 CNN 训练准备通道图像?
- android-studio - 如何为在Android中分配了多个角色的用户实现登录?
- javascript - 如何创建离线工作的网络应用程序?(例如,bulkresizephoto)
- javascript - 直接从相机上传图像到谷歌云存储
- java - 双向 jpa 休眠关系 @OneToMany @ManyToOne 失败,因为未存储父 ID