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

如何在Spring Boot和JavaScript中实现域名自动添加www前缀跳转

域名自动添加www前缀重定向实现方案

要实现访问https://example.com/dashboard自动跳转至https://www.example.com/dashboard,可分别通过以下方式实现:

Spring Boot 实现方式

推荐使用301永久重定向,对SEO更友好,以下为通用实现方案:
注:Spring Boot 3.x版本需将代码中的javax.servlet替换为jakarta.servlet

  • 自定义Servlet过滤器(全局生效,优先级最高)
    第一步:编写过滤器逻辑
    import javax.servlet.*;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    public class WwwRedirectFilter implements Filter {
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse resp = (HttpServletResponse) response;
            String host = req.getHeader("Host");
            // 排除本地调试环境、已经带www前缀的域名
            if (!host.startsWith("www.") && !host.contains("localhost") && !host.contains("127.0.0.1")) {
                // 保留原协议、路径、查询参数
                String redirectUrl = req.getScheme() + "://www." + host + req.getRequestURI() + 
                        (req.getQueryString() != null ? "?" + req.getQueryString() : "");
                // 301永久重定向
                resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
                resp.setHeader("Location", redirectUrl);
                return;
            }
            chain.doFilter(request, response);
        }
    }
    
    第二步:注册过滤器到Spring容器
    import org.springframework.boot.web.servlet.FilterRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class FilterConfig {
        @Bean
        public FilterRegistrationBean<WwwRedirectFilter> wwwRedirectFilter() {
            FilterRegistrationBean<WwwRedirectFilter> registrationBean = new FilterRegistrationBean<>();
            registrationBean.setFilter(new WwwRedirectFilter());
            // 匹配所有访问路径
            registrationBean.addUrlPatterns("/*");
            // 设置最高优先级,避免其他逻辑先执行
            registrationBean.setOrder(Integer.MIN_VALUE);
            return registrationBean;
        }
    }
    

JavaScript 实现方式

分为浏览器端前端实现和Node.js服务端实现两类:

  • 浏览器端实现(直接嵌入页面<head>标签最顶部,越早执行跳转效率越高)
    // 判断当前域名是否没有www前缀,排除本地调试场景
    if (!window.location.host.startsWith('www.') && !window.location.host.includes('localhost') && !window.location.host.includes('127.0.0.1')) {
        // 保留原协议、路径、查询参数、哈希锚点
        const newUrl = window.location.protocol + '//www.' + window.location.host + window.location.pathname + window.location.search + window.location.hash;
        // replace跳转不会在历史记录留存原域名记录,避免用户回退时重复触发跳转
        window.location.replace(newUrl);
    }
    
  • Node.js(Express框架)服务端实现
    app.use((req, res, next) => {
      const host = req.get('Host');
      if (!host.startsWith('www.') && !host.includes('localhost') && !host.includes('127.0.0.1')) {
        const redirectUrl = `${req.protocol}://www.${host}${req.originalUrl}`;
        // 301永久重定向
        res.redirect(301, redirectUrl);
        return;
      }
      next();
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 04:06:05