Tracking downloads is done by registering click handler callbacks for all links on a page that meet certail criteria (e.g. file extensions). (addClickListeners())
Thus the url that is tracked is not the url of the current page, it is the link-url, which is determined dynamically when the link is clicked. (logLink()) That’s why url-rewriting also needs to be done dynamically, e.g. by a rewrite function that could be registered as a hook.
I already browsed the source code but the only place I could find is setCustomRequestProcessing(). However at that stage the request is already serialized into a query string, so I’d have to split, decode, rewrite, re-encode and join the query-string, which is rather cumbersome…
It may be you found a missing feature (ability to customise download URLs?). Could you please create a bug report on: Issues · matomo-org/matomo · GitHub ? we may be able to help add this feature