You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中如何禁止URL多斜杠及非法路径访问?

Spring Boot 限制非法URL访问的实现方案

默认情况下,Spring Boot依赖的Servlet容器(如Tomcat)会自动对URL进行规范化处理:比如将/api/v1/hello//world合并为/api/v1/hello/world,将/api/v1/hello/../hello/world解析为/api/v1/hello/world,最终控制器会处理这些规范化后的路径。若要直接拒绝这类原始非法路径请求,可通过以下几种方式实现:

1. 容器配置禁用路径规范化

针对Tomcat容器,可通过配置关闭自动路径规范化,让非法路径直接返回400错误:

application.properties 配置

server.tomcat.normalize-path=false
server.tomcat.allow-non-standard-wrappers=false

application.yml 配置

server:
  tomcat:
    normalize-path: false
    allow-non-standard-wrappers: false

配置生效后,包含多斜杠或../的请求会被Tomcat直接拦截,返回400 Bad Request,不会到达控制器层。

2. 自定义拦截器全局拦截非法路径

如果需要自定义拦截规则(比如扩展更多非法路径模式),可以实现HandlerInterceptor进行全局拦截:

1. 创建拦截器类

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

public class InvalidUrlInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestUri = request.getRequestURI();
        // 检查请求路径是否包含非法模式
        if (requestUri.contains("//") || requestUri.contains("../")) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid URL path");
            return false;
        }
        return true;
    }
}

2. 注册拦截器

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new InvalidUrlInterceptor())
                .addPathPatterns("/**"); // 拦截所有请求路径
    }
}

通过这种方式,所有匹配非法模式的请求会被拦截,直接返回错误响应,无法进入控制器方法。

3. 控制器层面校验路径参数

如果仅需针对特定控制器方法做路径校验,可以在方法内手动检查路径变量:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1")
public class HelloController {
    @GetMapping("/hello/{segment}/world")
    public ResponseEntity<String> hello(@PathVariable String segment) {
        // 校验路径片段是否合法
        if (segment.contains("//") || segment.contains("../")) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid path segment");
        }
        return ResponseEntity.ok("Hello " + segment);
    }
}

这种方式适用于需要精准控制单个或少数接口路径合法性的场景。

内容的提问来源于stack exchange,提问作者dykovo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 16:32:33