Use pipe_through on Plug.Static to limit data access

Hi @Darkpingouin!

The router only invokes the pipelines for routes that it matches on. At the same time, plug Plug.Static works as a pass-through: i.e. if it finds a matching route, it serves it, otherwise it continues. So I am thinking you could probably do something like this in your router:

pipeline :static do
  plug Plug.Static, at: “img/files/”, from: “var/www/app/files/”, gzip: false
end

scope "/img/files" do
  pipe_through [:authenticate, :static]
  match "/*not_found", PageController, :not_found
end

In this case, if a static asset exists, it will be served. Otherwise, it will invoke PageController.not_found, which you can use to show a proper error message or just render the 404 page.

One other option is to not use Plug.Static at all and use Plug.Conn.send_file/3 directly.

7 Likes