URL rewrite best practice for subfolder cb app

I added an xml config file for web.rewrites. My subfolder coldbox app is at “root/api/” So my xml rule for the rewrite looks like this:
^/api/(.+)$
/api/index.cfm/$1
However, its not working, a GET request to “/api/timesheet/getteamtimesheet” responds with 404

In the debug console I see trace logs that seem to look for a match in the server rules first, then attempts to match from the rewrites rules in the xml, but doesn’t match.

Is the xml web.rewrite xml rules the best way to accomplish this? or can I accomplish the same thing with server rules? and how do I get it to work?

I added “regex(‘^/api/.+’) and not regex(‘.*\.(html|map|css|js|jpg|png|gif|ttf|woff)$’) → rewrite(/api/)” to server rules and the api is not accepting request, but all my valid endpoints resolve to my default event/action.

It depends on Web server you are using. You may find the rewrite rules here: https://coldbox.ortusbooks.com/the-basics/routing/requirements/rewrite-rules

You may also need to look at /config/Router.cfc

If possible, move the “/api” inside “/handlers”. So, you can call “/api/timesheet/getteamtimesheet”

I believe the rewrite function needs to change from “… → rewrite(/api/)” to " … → rewrite(/api/${1})"

complete rule:
regex(‘/api/(.*)’) → rewrite(‘/api/${1}’)

Yes, ${1} is the Undertow syntax for regex backreferences. If you store that rule in your server.json, you’ll need to escape the backreference with a backslash so CommandBox doesn’t try to resolve it as a system setting placeholder.

As far as why your regex isn’t matching the incoming request, I’d need to see the full trace logs from the console to understand all the parameters. You defo want to use the server rule. The Tuckey XML rewrites are deprecated and don’t even work in multi-site mode without special configuration (since they are stuck in the servlet).

1 Like

Ok my rewrite rule was wrong. I was rewriting the request to the same thing - this /api/user would get rewritten to this /api/user. Pretty dumb, right.

Here is the correct way the rule should be written and how to escape the regex backreference:
regex(‘/api/(.*)’) → rewrite(‘/api/index.cfm/\\${1}’)

So using server rules in server.json is the way to go. Thank Brad.

1 Like