You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从非默认路径提供静态文件?Plug.Static路径适配问题

解决Plug.Static自定义路径后static_path生成URL不匹配的问题

你遇到的问题核心是Phoenix的static_path函数默认使用的静态资源前缀,和你新配置的Plug.Static的:at路径没同步上。这里有几个简单有效的解决方法:

方法一:全局配置Endpoint的静态路径前缀

最省心的方式是在项目配置里全局指定静态资源的路径,这样所有static_path调用都会自动适配新前缀。

找到你的config/config.exs(或者对应环境的配置文件,比如dev.exs),定位到Endpoint的配置块,添加或修改static_path选项:

config :my_project, MyProjectWeb.Endpoint,
  # 保留原有其他配置...
  static_path: "/my_project/another_path/assets"

修改完成后重启服务器,之后static_path生成的URL就会自动带上新前缀,比如host.com/another_path/assets/my-picture-hash。

方法二:调用static_path时显式指定前缀

如果不想全局修改配置,或者需要针对部分页面使用不同前缀,可以在调用static_path时手动指定:at参数:

<img class='picture' src='<%= static_path(@conn, "/myPicture.png", at: "/my_project/another_path/assets") %>'>

这样这个特定的资源链接就会生成符合预期的路径。

额外注意事项

  1. 确保你的Plug.Static配置在Endpoint中正确设置,且顺序在路由之前(这是Phoenix的常规做法,避免路由拦截静态资源请求):
defmodule MyProjectWeb.Endpoint do
  use Phoenix.Endpoint, otp_app: :my_project

  # 其他插件配置...

  plug Plug.Static,
    at: "/my_project/another_path/assets",
    from: :my_project,
    gzip: true

  plug MyProjectWeb.Router
end
  1. 如果你用的是Phoenix新版本推荐的Routes.static_path函数,解决逻辑完全一致——要么全局配置static_path,要么调用时添加:at参数。

内容的提问来源于stack exchange,提问作者kace91

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 21:04:06