Redirect to a different host in Spring Boot (non-www to www URL)

只谈情不闲聊 提交于 2019-12-02 09:04:57

I have to answer my own question here as I found out that there is no Java equivalent configuration for this library, as it was last maintained in 2012. The solution is a mix of Java and XML configuration. This configuration can be avoided if you use a reverse proxy server. However, I wanted to avoid that and have the single application server to do all sorts of things. So here it goes:

The configuration file:

@Configuration
public class UrlRewriteConfig extends UrlRewriteFilter {

    private UrlRewriter urlRewriter;

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

    @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();
    }
}

The project structure:

And the urlrewrite.xml file:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE urlrewrite
        PUBLIC "-//tuckey.org//DTD UrlRewrite 3.0//EN"
        "http://www.tuckey.org/res/dtds/urlrewrite3.0.dtd">

<urlrewrite>
    <rule>
        <name>SEO Redirect and Secure Channel</name>
        <condition name="host" operator="equal">^example.com</condition>
        <from>^(.*)$</from>
        <to type="permanent-redirect">https://www.example.com$1</to>
    </rule>
</urlrewrite>

A very important point to be noted, is that I had to remove my insecure http to https redirection in the Undertow Server configuration as it threw an error - "TOO MANY REDIRECTS". So what i did is I kept two ports opened - 80 and 443 for insecure and secure connections and the tuckey configuration does the all sorts of redirection, from http to https and from non-www to www. I hope it helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!