Nginx转发请求至Docker容器内Pinpoint-web服务遇404错误
问题:Nginx反向代理Pinpoint-web服务出现404错误
环境配置
docker-compose.yml 配置
nginx: image: nginx:1.23.3 volumes: - ./nginx/default.conf:/etc/nginx/conf.d/default.conf - ./nginx/src:/etc/nginx/html depends_on: - pinpoint-web restart: always ports: - 81:80 networks: support-network: pinpoint-web: image: "pinpointdocker/pinpoint-web:${PINPOINT_VERSION}" restart: always expose: - "9997" ports: - "9997:9997" - "8080:8080" networks: support-network:
Nginx 原错误配置
upstream pinpoint-web { server pinpoint-web:8080; } server { listen 80; location /pinpoint-web { rewrite /pinpoint-web/(.*) http://pinpoint-web:8080/$1 break; proxy_pass http://pinpoint-web; } }
问题现象
访问http://localhost:81/pinpoint-web时返回404错误,响应内容:
{ "timestamp": 1678301663635, "status": 404, "error": "Not Found", "message": "No message available", "path": "/pinpoint-web", "data": null }
Nginx相关日志:
2023-03-08 13:54:19 2023/03/08 18:54:19 [notice] 1#1: start worker process 29 2023-03-08 13:54:19 2023/03/08 18:54:19 [notice] 1#1: start worker process 30 2023-03-08 13:54:19 2023/03/08 18:54:19 [notice] 1#1: start worker process 31 2023-03-08 13:54:19 2023/03/08 18:54:19 [notice] 1#1: start worker process 32 2023-03-08 13:54:23 172.22.0.1 - - [08/Mar/2023:18:54:23 +0000] "GET /pinpoint-web HTTP/1.1" 404 139 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.63" "-"
解决方案
问题根源
原配置的rewrite /pinpoint-web/(.*)规则仅匹配带斜杠的子路径(如/pinpoint-web/index),无法匹配/pinpoint-web(无斜杠)的请求。此时请求会直接转发到后端http://pinpoint-web/pinpoint-web,而Pinpoint-web的根路径为/,因此返回404。
修正后的Nginx配置
方案一:通过rewrite统一处理路径
upstream pinpoint-web { server pinpoint-web:8080; } server { listen 80; location /pinpoint-web { # 将不带斜杠的请求重定向到带斜杠的路径 rewrite ^/pinpoint-web$ /pinpoint-web/ permanent; # 去掉/pinpoint-web前缀后转发到后端 rewrite ^/pinpoint-web/(.*)$ /$1 break; proxy_pass http://pinpoint-web; # 添加代理头确保后端正确识别请求 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_pass自动截断路径特性
upstream pinpoint-web { server pinpoint-web:8080; } server { listen 80; # 匹配带斜杠的子路径,自动截断前缀转发 location ^~ /pinpoint-web/ { proxy_pass http://pinpoint-web/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } # 单独处理不带斜杠的请求,重定向到带斜杠的路径 location = /pinpoint-web { return 301 /pinpoint-web/; } }
验证
修改配置后重启Nginx容器:
docker-compose restart nginx
访问http://localhost:81/pinpoint-web会自动重定向到http://localhost:81/pinpoint-web/,并成功转发到Pinpoint-web服务。
内容的提问来源于stack exchange,提问作者Muthu
相关产品推荐
相关产品推荐

