Using URL Rewrite in WildFly 27

Using URL rewrite results in URLs that are easier to read and for search engines to index.

March 27, 2023

For our articles on various business and technology topics, we wanted to make the URL for each of those use a more friendly format. This required changing URLs of the form BlogEntry?id=7 to be BlogEntry/configure_wildfly_27_for_ISB. Not only does this result in a better URL for end users but it also gives a nice, unique canonical URL for search engines.

For this task we needed to use the filter/rewrite capabilities of WildFly. The hard part was finding documentation on how URL rewrite works. We found some documentation, but it didn't really help us understand what to do.

After much experimenting, we were able to get URL rewrite to work as we wanted. It requires two commands to be entered in the wildfly CLI:

/subsystem=undertow/server=default-server/host=default-host/filter-ref=blog-rewrite:add(predicate="method(GET) and regex('/BlogEntry/(.*)')")



Let's look at each of these in turn

Incoming URL match rule

The first is to match the incoming URL, i.e. what appears in the browser's URL bar. In our case, we want the rule to match any URL that begins with "/BlogEntry/" and is followed by anything. So a URL of /BlogEntry/this_article would match this rule.

Note that this rule has two components: a requirement that the request uses the GET method (as opposed to POST) and a regular expression. Our regular expression matches any URL that begins with "/BlogEntry/". Any other URLs will not be matched by this rule and thus will not enter the rewrite engine.

Resulting URL rule

Having captured the relevant URLs, we are ready to rewrite them. Our second rule tells the rewrite engine how to do that. It says that the resulting URL should begin with "/BlogEntry?id=". This is the first part of the rewrite. This is then followed by "$${1}". This last part is critical. It matches to the last portion of the original, incoming URL. Having passed through this rule, the resulting URL will be in the form /BlogEntry?id=this_article. This form matches our servlet and allows it to retrieve the correct article from the database.