Reputation: 853
I'm using Plug.Static to serve static files from my server. The "default" way to do so would be to configure it like so:
plug Plug.Static,
at: "/my_project/assets",
from: :my_project,
gzip: true
and then I can consume the files in priv/static in the html using for example:
<img class='picture' src='<%= static_path(@conn, "/myPicture.png") %>'>
So far so good. However, if I want to serve the files from priv/static at a different path, and I use
plug Plug.Static,
at: "/my_project/another_path/assets",
from: :my_project,
gzip: true
Now I can't access the files using static_path, since it's still resolving to host.com/assets/my-picture-hash
instead of host.com/another_path/assets/my-picture-hash
, which is the intended behaviour.
How can I get the actual path of a hashed file when it's not exposed in the default path?
Upvotes: 1
Views: 1941
Reputation: 15515
Are you sure your first example is working? I think that configuration only works when called as static_path(@conn, "/my_project/assets/myPicture.png)
.
So your second example works when called as static_path(@conn, "/my_project/another_path/assets/myPicture.png")
It looks like perhaps you have the :at
and :to
options mixed up. This is from the Plug.Static
docs:
:at
- the request path to reach for static assets. It must be a string.
:from
- the file system path to read static assets from. It can be either: a string containing a file system path, an atom representing the application name (where assets will be served frompriv/static
), or a tuple containing the application name and the directory to serve assets from (besidespriv/static
).
So to answer the title of your question (how can I serve static files from a non-default path?); if you want to serve files from a different path instead of the default priv/static
in your application folder, shouldn't it be:
plug Plug.Static, at: "/uploads", from: "/some/other/path"
And to show the image located on your disk at /some/other/path/myPicture.png
(this is an absolute path, not relative to your application):
<img class="picture" src="<%= static_path(@conn, "/uploads/myPicture.png") %>">
(If this is still not working and you have added this as a new Plug.Static
after the default one: place it before the default static plug.)
Edit:
And of course, if you want to serve the static assets from the default path (priv/static
in your app folder) but with a custom url, you can do:
plug Plug.Static, at: "/some/path", from: :my_project
and serve them as:
<img class="picture" src="<%= static_path(@conn, "/some/path/myPicture.png") %>">
Upvotes: 3