![如何通过 nginx 将两个 URL 重写到同一个端点?](https://linux22.com/image/747056/%E5%A6%82%E4%BD%95%E9%80%9A%E8%BF%87%20nginx%20%E5%B0%86%E4%B8%A4%E4%B8%AA%20URL%20%E9%87%8D%E5%86%99%E5%88%B0%E5%90%8C%E4%B8%80%E4%B8%AA%E7%AB%AF%E7%82%B9%EF%BC%9F.png)
我有两个 HTTP 端点如下
http://me11.example.local/api/foo
http://me11.example.local/api/boo
我想将它们重定向到两个不同的端点。在我的配置文件中,它仅适用于一个 URL。我该如何为两个端点配置它?我的 Nginx 配置文件如下所示
server {
listen 80;
listen [::]:80;
server_name me11.example.local;
location /{
rewrite ^/api/foo / last;
proxy_pass http:localhost:5000;
}
location /{
rewrite ^/api/boo / last;
proxy_pass http:localhost:6000;
}
}
使用此配置我收到以下错误
duplicate location and so on
如果我删除一个位置块,它可以正常工作,但我需要它对两个端点都起作用。
我该如何解决这个问题?
答案1
您可以尝试类似以下操作:
server {
listen 80;
listen [::]:80;
server_name me11.example.local;
if ($request_uri = "/api/foo") {
rewrite ^/api/foo / last;
proxy_pass http:localhost:5000;
}
if ($request_uri = "/api/boo") {
rewrite ^/api/boo / last;
proxy_pass http:localhost:6000;
}
}
但要注意 nginx 中的 if:https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/
您可以在这里检查 nginx.conf 变量:http://nginx.org/en/docs/varindex.html
问候,