jjv360
jjv360

Reputation: 4140

Catch-all URL rewrite on Google App Engine (Java)

I'm trying to create a short URL for a GAE app, so I used UrlRewriteFilter, but I can't get it set up correctly. Basically, the user is given this:

and the page that they should be redirected to is

At the moment it's working with the urlrewrite.xml file like this:

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

    <rule>
        <from>/([0-z]+)</from>
        <to last="true">/vote.jsp?id=$1</to>
    </rule>

</urlrewrite>

The problem is that all URLs now redirect to this, so for example

still runs the page at vote.jsp. What should I do to get it to redirect only when the URL isn't found?

Upvotes: 2

Views: 1249

Answers (1)

Tom
Tom

Reputation: 26829

What about the following rule:

<rule>
   <from>^/([\w-]+)$</from>
   <to last="true">/vote.jsp?id=$1</to>
</rule>

Where [\w-]+ is at least one any word character (letter, number, underscore) including - (dash character). You use ^ and $ to anchor beginning and end of checked text.


UrlRewriteFilter documentation says

When executing a rule the filter will (very simplified) loop over all rules and for each do something like this psuedo code:

Pattern.compile(<from> element); pattern.matcher(request url);
matcher.replaceAll(<to> element); 
if ( <condition> elements match && matcher.find() ) {
    handle <set> elements (if any)
    execute <run> elements (if any)
    perform <to> element (if any) 
}

That's why you have to use beginning (^) and end ($) string regular expression anchors

Upvotes: 2

Related Questions