我正在开发微服务架构,需要将 Nginx 设置为反向代理,以根据请求 URL 将流量路由到不同的服务。这是我当前的设置:
这是我当前的 Nginx 配置的片段:
upstream admin {
server admin:8000;
}
upstream announcements {
server announcements_api:8080;
}
upstream statistics {
server statistics_api:8081;
}
server {
listen 80;
location /admin(/.*)?$ {
proxy_pass http://admin;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $host;
client_max_body_size 100M;
}
location ~* /announcements(/.*)?$ {
proxy_pass http://announcements$request_uri;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $host;
client_max_body_size 100M;
proxy_redirect off;
}
location ~* /statistics(/.*)?$ {
proxy_pass http://statistics$request_uri;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $host;
client_max_body_size 100M;
proxy_redirect off;
}
# Serve static and media files if needed
location /media/ {
alias /usr/share/nginx/media/;
}
location /static/ {
alias /usr/share/nginx/staticfiles/;
}
}
但是,我遇到了问题,即对
/admin/announcement/
的请求似乎未正确路由。它路由到/anouncement/
服务导致404,我的公告服务可能有api/v1/announcement/something-else/
,或者只是从/announcment/
开始,而且这个服务中也有/category/
,但不知道如何实现它。 因为这里不需要正则表达式 -
/announcement(/.*)?$
会匹配 /admin/announcement(/.*)?$
并且确定优先级很痛苦。
您应该使用简单的匹配,如下所示:
location /admin {
proxy_pass http://admin;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $host;
client_max_body_size 100M;
}
根据您的宏服务的期望,您可能需要调整
proxy_pass
或进行重写。
有关更多详细信息,请参阅文档:https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass