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

如何为steampixel/simple-php-router设置静态资源目录并添加图片?

解决方案

是否需要添加public文件夹?

不是必须,但推荐使用public文件夹作为网站根目录——它能把敏感的PHP代码(路由配置、业务逻辑等)隔离在公开访问范围外,提升安全性。如果不想额外创建public文件夹,也可以直接通过路由规则或服务器配置让assets目录可访问。

方法1:不使用public文件夹,通过路由配置公开assets

steampixel/simple-php-router支持添加静态文件路由规则,在你的路由配置文件中加入以下代码:

// 拦截所有/assets/开头的请求,返回对应文件
Router::add('GET|POST', '/assets/[*:file]', function($file) {
    $filePath = __DIR__ . '/assets/' . $file;
    // 检查文件是否存在
    if (!file_exists($filePath)) {
        http_response_code(404);
        exit;
    }
    // 设置正确的文件类型头
    $mime = mime_content_type($filePath);
    header("Content-Type: $mime");
    // 输出文件内容
    readfile($filePath);
    exit;
});

配置完成后,访问/assets/img/name.jpg即可获取对应图片文件。

方法2:使用public文件夹(推荐方案)

  1. 新建public目录,将assets文件夹和路由入口文件(比如index.php)都移入其中;
  2. 配置Web服务器,将网站根目录指向public文件夹:
    • Apache:修改虚拟主机配置或项目根目录的.htaccess:
      DocumentRoot "/你的项目路径/public"
      <Directory "/你的项目路径/public">
          AllowOverride All
          Require all granted
      </Directory>
      
    • Nginx:修改server块的root指令:
      server {
          root /你的项目路径/public;
          index index.php;
          # 其他Nginx配置...
      }
      
  3. 此时服务器会直接处理/assets/开头的静态请求,无需额外配置路由,访问效率更高。

前端引用验证

无论用哪种方式,首页HTML中都可以直接这样引用图片:

<img src="/assets/img/name.jpg" alt="示例图片">

访问首页即可看到图片正常加载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 07:52:06