How to capture specific parameters in netlify.toml redirect?

I have this problem where my assets folder isn’t correctly being queried. The app works fine for URLs without a trailing slash, but when you add a trailing slash, it looks for the asset/static files relative to the url path. I had the same problem when I was testing locally with Nginx and was able to fix it by adding the following in my .conf file:

location ~ ^/.*/assets/(.*) {
        alias /etc/nginx/html/assets/$1;
    }

This forces nginx to look for assets files directly in the assets folder regardless of the url.

I’m trying to do the same thing in my netlify.toml file but I’m not sure how to capture specific parameters. Ideally, I want to do something similar but not sure if I can capture specific parameters like you can with the nginx.conf file.

[[redirects]]
  from = "^/.*/assets/(.*)"
  to = "/assets/:1"
  status = 200
  force = true

I would like to first point out that, while the syntax you are using for the redirect rule is a valid Perl-compatible regular expression, the redirects rules at Netlify do not use this syntax.

Also, if you use two wildcard matches in a redirect, there is no way to reference them separately in the “to” portion of the rule.

If there are no subdirectories under /assets/, then the following redirect rule will do what is required:

[[redirects]]
  from = "/*/assets/:file"
  to = "/assets/:file"
  status = 200

The changes made above are:

  • removing the regex in the “from” line
  • using a named placeholder for the filename after /assets/
  • removed force = true

I removed the force = true because it seemed unnecessary. The use of force = true causes a redirect to be used even when a file exists at the original “from” location. As you know the files will never exist there, forcing the rule isn’t necessary. You can add it back in if you like, though.

If that redirect rule above doesn’t work or if there are other question, please let us know.

1 Like

exactly what I was looking for, thanks!