场景描述

域名请求网关使用的地址如 xxx.com/gateway/,返回404报错

原因是nginx转发的时候 /gateway/ 也被用来寻址

gateway 没办法设置 context-path ,针对这个场景可以自定义拦截器来处理

@Configuration
public class ContextPathConfig {
 
    @Bean
    @ConditionalOnProperty("server.servlet.context-path")
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public WebFilter contextPathWebFilter(ServerProperties serverProperties){
        String contextPath = serverProperties.getServlet().getContextPath();

        return (serverWebExchange, webFilterChain) ->{
            ServerHttpRequest request = serverWebExchange.getRequest();
            String requestPath = request.getURI().getPath();

            if(requestPath.contains(contextPath)){
                String newPath = requestPath.replaceFirst(contextPath, "");
                ServerHttpRequest newRequest = request.mutate()
                                .path(newPath).build();
                return webFilterChain.filter(serverWebExchange.mutate()
                                .request(newRequest)
                                .build()
                );
            }else {
                throw new ResponseStatusException(HttpStatus.NOT_FOUND);
            }
        };
    }
}

application.yml增加 context-path配置

server:
  servlet:
    context-path: /gateway
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐