Search code examples
url-rewritingtuckey-urlrewrite-filter

Tuckey UrlRewriteFilter Not Working With Multiple Conditions for Host Not Equal


When my URL is localhost:8080, the rule below for Tuckey UrlRewriteFilter wrongly always results in localhost:8080 redirecting to www.example.com.

That behaviour for seems contrary to Tuckey UrlRewriteFilter reference manual!

What I want is for localhost:8080 to remain unchanged without redirection, to allow testing on local computer.

I wish to avoid unwanted URLs which are NOT at the example.com domain from being indexed by search engines. The unwanted URLs have a different domain but point to the same/duplicate example.com pages.

<urlrewrite>
    <rule>
        <name>Avoid wrong hostname's pages being indexed by search engines</name>

        <condition name="host" operator="notequal" next="and">www.example.com</condition>
        <condition name="host" operator="notequal" next="and">localhost:8080</condition>

        <from>^/(.*)</from>
        <to type="permanent-redirect" last="true">http://www.example.com/$1</to>
    </rule>

Alternative:

I also tried it another way: removing all condition elements, and altering "from" to be:

   <from>^/(^www.example.com|^localhost:8080)(\?.*)?$</from>

i.e. not equal to example.com and not equal to localhost -- but that has same problem.


Solution

  • I had the same problem as you do but couldn't find a solution using tuckey. I end up solving this compatibility of localhost-test and domain-name-consistency by using the interceptor in Spring. My code is like this

    public boolean preHandle(HttpServletRequest request,
        HttpServletResponse response, Object handler) throws Exception {
    String url = request.getRequestURL().toString();
    if (!url.startsWith("http://localhost") && !url.startsWith("http://www.example.com")){
        response.sendRedirect("http://www.example.com"+request.getRequestURI());
        return false;
    }
    return true;}
    

    but there will be the necessary overhead to check in every request. Hope this helps!