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

能否用单个Spring Boot Controller接收多子域名API请求?

用Spring Boot Controller匹配固定后缀域名的请求

完全可以实现,下面是两种实用的方案:

方案一:通过@RequestMapping的host属性直接匹配(推荐)

Spring的@RequestMapping注解支持通过host属性配置通配符域名,直接过滤符合后缀规则的请求,代码示例如下:

import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
// 匹配所有以.domain.subdomain.it结尾的域名
@RequestMapping(host = "*.domain.subdomain.it")
public class WildcardDomainController {

    // 匹配该域名下的所有路径请求
    @RequestMapping("/**")
    public String handleDomainRequests(@RequestHeader("Host") String currentHost) {
        // 这里编写你的业务逻辑
        return "处理来自域名:" + currentHost + " 的请求";
    }
}

这种方式的优势是Spring会自动拦截符合域名规则的请求,无需手动判断,完全符合Spring的请求映射规范。

方案二:通过Host头手动校验

如果需要更灵活的域名校验逻辑,可以先匹配所有路径请求,再通过@RequestHeader获取请求的Host头进行后缀判断:

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

@RestController
@RequestMapping("/**")
public class WildcardDomainController {

    private static final String TARGET_DOMAIN_SUFFIX = ".domain.subdomain.it";

    public String handleAllRequests(@RequestHeader("Host") String host) {
        if (host.endsWith(TARGET_DOMAIN_SUFFIX)) {
            // 处理业务逻辑
            return "处理来自域名:" + host + " 的请求";
        } else {
            // 对不符合规则的请求返回404
            throw new ResponseStatusException(HttpStatus.NOT_FOUND);
        }
    }
}

注意事项

  • 确保所有目标域名(example1.domain.subdomain.it、example2.domain.subdomain.it等)都已解析到你的应用服务器IP,服务器能正常接收这些域名的请求。
  • 如果存在多个Controller,可通过@Order注解调整请求映射的优先级,避免冲突。

内容的提问来源于stack exchange,提问作者S-Wing

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 08:22:40