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

Laravel中.htaccess图片转WebP规则在artisan serve下失效求助

问题原因

artisan serve 启动的是PHP内置Web服务器,它完全不支持Apache的.htaccess配置文件,所以你写的图片重定向规则、Header设置等都不会生效。只有Apache(或兼容.htaccess的服务器如LiteSpeed)才会解析这类配置。

解决方案

下面提供两种适配PHP内置服务器的替代方案:

方案1:用Laravel中间件处理图片重定向

这种方案贴合Laravel生态,无需修改启动方式:

  1. 生成中间件
    运行命令创建图片重定向中间件:
php artisan make:middleware WebpImageRedirect
  1. 编写中间件逻辑
    打开app/Http/Middleware/WebpImageRedirect.php,替换handle方法:
public function handle(Request $request, Closure $next)
{
    // 仅处理JPG/JPEG/PNG图片请求
    $path = $request->path();
    if (!preg_match('/\.(jpg|jpeg|png)$/i', $path)) {
        return $next($request);
    }

    // 检查浏览器是否支持WebP格式
    if (str_contains($request->header('Accept'), 'image/webp')) {
        // 替换图片后缀为webp,构建目标文件路径
        $webpPath = preg_replace('/\.(jpg|jpeg|png)$/i', '.webp', $path);
        $fullPath = public_path($webpPath);

        // 若对应WebP文件存在,执行301重定向
        if (file_exists($fullPath)) {
            return redirect($webpPath, 301)->header('Content-Type', 'image/webp');
        }
    }

    return $next($request);
}
  1. 注册中间件
    打开app/Http/Kernel.php,将中间件添加到web中间件组(或全局中间件):
protected $middlewareGroups = [
    'web' => [
        // ... 其他已有中间件
        \App\Http\Middleware\WebpImageRedirect::class,
    ],
];

方案2:自定义PHP内置服务器路由脚本

直接替换PHP内置服务器的默认路由逻辑,模拟.htaccess的功能:

  1. 创建server.php文件
    在项目根目录新建server.php,内容如下:
<?php

$uri = $_SERVER['REQUEST_URI'];

// 处理图片重定向逻辑
if (preg_match('/\.(jpg|jpeg|png)$/i', $uri) && str_contains($_SERVER['HTTP_ACCEPT'] ?? '', 'image/webp')) {
    $webpUri = preg_replace('/\.(jpg|jpeg|png)$/i', '.webp', $uri);
    $filePath = __DIR__ . '/public' . $webpUri;

    if (file_exists($filePath)) {
        header('Content-Type: image/webp');
        header('Vary: Accept');
        header('Location: ' . $webpUri, true, 301);
        exit;
    }
}

// 保留Laravel内置服务器的原始逻辑
$uri = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {
    return false;
}

require_once __DIR__.'/public/index.php';
  1. 用自定义脚本启动服务器
    运行以下命令代替artisan serve:
php -S localhost:8000 server.php

备选方案:继续使用Apache/Nginx

如果你更习惯.htaccess的配置方式,直接用XAMPP(Apache)运行Laravel即可,确保:

  • Laravel项目的根目录指向public文件夹
  • Apache已启用mod_rewrite和mod_headers模块

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 21:45:28