How to convert a subdomain to a path with Embedded Tomcat 8 and Spring boot

前端 未结 4 1422
执念已碎
执念已碎 2021-02-06 04:57

How to rewrite subdomains to paths?

Example:

  • foo.bar .example.com --> example.com /foo/bar

Or better woul

4条回答
  •  旧时难觅i
    2021-02-06 05:24

    It worked for me. Hope it works for others too.

    Please use the following dependency


             
               org.tuckey
               urlrewritefilter
               4.0.4
             
    

    Created urlrewrite.xml in resource folder

     
     
    
    
    
        Domain Name Check
        www.userdomain.com
        ^(.*)$
        http://www.userdomain.com$1
    
    


    Added in main ApplicationRunner.java

    @Bean
    public FilterRegistrationBean tuckeyRegistrationBean() {
        final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(new CustomURLRewriter());
        return registrationBean;
    }
    

    And created a CustomURLRewriter

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.core.env.Environment;
    import org.springframework.core.io.ClassPathResource;
    import org.tuckey.web.filters.urlrewrite.Conf;
    import org.tuckey.web.filters.urlrewrite.UrlRewriteFilter;
    import org.tuckey.web.filters.urlrewrite.UrlRewriter;
    import javax.servlet.*;
    import java.io.InputStream;
    
    public class CustomURLRewriter extends UrlRewriteFilter {
    private UrlRewriter urlRewriter;
    
    @Autowired
    Environment env;
    
    @Override
    public void loadUrlRewriter(FilterConfig filterConfig) throws ServletException {
        try {
            ClassPathResource classPathResource = new ClassPathResource("urlrewrite.xml");
            InputStream inputStream = classPathResource.getInputStream();
            Conf conf1 = new Conf(filterConfig.getServletContext(), inputStream, "urlrewrite.xml", "");
            urlRewriter = new UrlRewriter(conf1);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }
    
    @Override
    public UrlRewriter getUrlRewriter(ServletRequest request, ServletResponse response, FilterChain chain) {
        return urlRewriter;
    }
    
    @Override
    public void destroyUrlRewriter() {
        if(urlRewriter != null)
            urlRewriter.destroy();
    }
    }
    

提交回复
热议问题