In config/routes.rb, how do you write a *path catch-all route, and why can it break Active Storage URLs if added carelessly?
answer
- named glob, params[:path]
- extension split into format
- must be the last line
- engine routes load after yours
- exclude /rails/ with a lambda
basics
~20 sAdd match "*path", to: "errors#not_found", via: :all as the last route. Engine routes such as Active Storage's /rails/active_storage/... are drawn after the app's file, so the catch-all shadows them unless a lambda constraint excludes /rails/.
solid answer
~40 sA glob segment `*path` matches the rest of the URL across slashes: `/a/b/c` gives `params[:path] == "a/b/c"`. By default a trailing extension is split off into `params[:format]`, so `format: false` is needed if `.html` must stay in the path. A catch-all goes at the very bottom, because earlier lines win. The catch is that Active Storage, Action Mailbox and some gems draw their routes into the app's route set after `config/routes.rb`, so those routes rank below everything in your file, catch-all included. Blob URLs then hit your 404 action. Guard it with `constraints: ->(req) { !req.path.start_with?("/rails/") }`, which makes the catch-all pass on those paths. Also ask whether you need it at all: an unmatched path already ends as a 404.
code
ruby · 9 lines# config/routes.rb (last lines)
Rails.application.routes.draw do
# ... all other routes above ...
get "journal/*rest", to: redirect("/stories/%{rest}"), format: false
match "*path", to: "errors#not_found", via: :all,
constraints: ->(req) { !req.path.start_with?("/rails/") }
endgo deeper
Recall that *path captures the rest of the URL with slashes and that a catch-all goes on the last line.
Explain how globs interact with the optional format and why match needs via: when used for a catch-all.
Diagnose broken blob URLs as a catch-all shadowing lower-priority framework routes and fix it with a passing lambda constraint.
Prefer scoped globs and the standard 404 path over a global catch-all, and own the list of framework prefixes it must never swallow.
## Glob segments A **glob** (or wildcard) segment is a path placeholder prefixed with a star. Unlike `:name`, which stops at a slash, a glob takes the rest of the path, slashes included: ```ruby get "journal/*rest", to: "journal#legacy" # /journal/2019/06/our-venue => params[:rest] == "2019/06/our-venue" ``` The rules worth knowing: - The glob must have a **name** (`*rest`, `*path`); a bare star cannot be parsed. - It can sit anywhere: `get "albums/*section/:photo"` puts the middle into `section` and the last piece into `photo`. - It is **non-greedy** and must match at least one character. - By default a trailing extension becomes the **format**: `/journal/our-venue.html` gives `rest == "our-venue"` and `format == "html"`. Pass `format: false` to keep `our-venue.html` in `rest`. ## The catch-all A **catch-all** is a glob route that matches every path, usually for a custom not-found page or to hand unknown URLs to a single-page front end: ```ruby match "*path", to: "errors#not_found", via: :all ``` `match` needs an explicit verb list; `via: :all` accepts every method, while `get "*path"` would leave POSTs to unknown URLs to the normal routing error. Since the routes in your file are tried in the order they are written, the catch-all belongs on the **last line**; anything below it can never be reached. ## How it breaks Active Storage Active Storage does not mount an engine at a prefix. Its `config/routes.rb` calls `Rails.application.routes.draw` and adds routes such as `/rails/active_storage/blobs/redirect/:signed_id/*filename` straight into **your** route set. Action Mailbox does the same for its ingress routes, and so do some gems. Those files are loaded **after** your application's `config/routes.rb`, so their routes rank below every line you wrote; Rails' own test suite pins this down as "routes in engines have lower priority than application ones". The result, step by step: 1. A view renders an image with a `/rails/active_storage/blobs/redirect/...` URL. 2. The browser requests it. 3. Your `*path` catch-all matches first and renders the not-found page. 4. The Active Storage route that should have served the blob is never reached. The fix is a constraint that makes the catch-all step aside: ```ruby match "*path", to: "errors#not_found", via: :all, constraints: ->(req) { !req.path.start_with?("/rails/") } ``` When the lambda returns false the route **passes**, and the router continues to the lower-priority framework routes. The development-only `/rails/info` pages are not affected, because Rails prepends them ahead of your file. ## Do you need a catch-all at all? | Goal | Better tool | |---|---| | A branded 404 page | The app's exceptions handling, which already turns an unmatched path into a 404 | | Old URLs moved under a new prefix | A narrow glob with `redirect`, like `get "journal/*rest", to: redirect("/stories/%{rest}")` | | A front-end router owns some paths | A glob scoped to that prefix, plus a constraint for HTML requests | A narrow glob such as `journal/*rest` cannot shadow anything outside `/journal`, which makes it far safer than a global `*path`. ## Checks before shipping one - Put it last and keep it the only global glob. - Exclude `/rails/` and any prefix a gem draws into your routes. - Decide the verb list on purpose; `via: :all` also catches stray POSTs and PATCHes. - Remember `format: false` when the extension matters. - Look at the listed routes to confirm the catch-all really is at the bottom of your section, and request a real blob URL in a test. ## A front-end fallback without collateral damage When a JavaScript front end owns its own paths, the catch-all should answer only page loads, not API calls, images or framework routes: ```ruby get "*path", to: "spa#index", constraints: ->(req) { req.format.html? && !req.path.start_with?("/rails/") } ``` `req.format.html?` keeps JSON and asset requests out, so a missing API endpoint still fails as a routing error instead of returning an HTML shell with status 200. A catch-all is a blunt tool. Scoped globs and redirects solve most legacy-URL needs without the risk.
- In Rails, what does get "pages/*slug" put in params for /pages/faq/venues.json?`params[:slug]` is `"faq/venues"` and `params[:format]` is `"json"`, because a glob is non-greedy and the optional format captures the extension by default. With `format: false` on the route, `params[:slug]` becomes `"faq/venues.json"` and there is no format param.
- Why does a catch-all in config/routes.rb not hide the development /rails/info/routes page?In development Rails adds the `/rails/info` routes with `routes.prepend`, so they sit ahead of everything in your file. Active Storage and Action Mailbox routes are drawn by their own routes files after yours, which is why those are shadowed and the info pages are not.
- Framework routes like Active Storage's always outrank anything in config/routes.rb
- A glob segment stops at the next slash like :id does
- A catch-all can go anywhere because Rails picks the most specific route
- An anonymous * without a name is a valid catch-all
- Rails needs a catch-all route to return 404 for unknown paths