React应用静态文件加载异常——MIME类型问题求助
React应用静态文件Content-Type错误问题
问题描述
React应用静态文件无法正常加载:请求JavaScript和CSS文件时返回的Content-Type为text/html,而非预期的application/javascript或text/css。
详细信息
- URL:https://emergencyplumbersmanchester.com
- 构建目录:
/home/wwwplumb/emergencyplumbersmanchester.com/build - 主域名:https://plumbingmanchester.co.uk
- 文件夹结构:build目录下包含static文件夹、index.html及其他构建生成的文件
服务器详情
- 托管套餐:Silver 100
- 服务器名称:s938
- cPanel版本:124.0 (build 26)
- Apache版本:2.4.62
- 数据库版本:10.6.21-MariaDB
- 操作系统:Linux
- IP地址:无
观察结果
- 请求静态文件(如
main.9b9eb604.js和main.724539ac.css)返回text/html类型。 - 静态文件似乎被重定向到
index.php并返回index.html内容。 .htaccess规则疑似导致静态文件无法正常加载。
已采取的步骤
- 更新
.htaccess添加MIME类型设置:
<IfModule mod_mime.c> AddType application/javascript .js AddType text/css .css AddType application/json .json </IfModule>
- 设置构建目录权限:
chmod -R 777 /home/wwwplumb/emergencyplumbersmanchester.com/build
- 验证构建输出及文件位置。
- 尝试直接访问静态文件,仍收到
text/html响应。
index.php代码
<?php $react_build_path = __DIR__ . '/build'; $request_uri = $_SERVER['REQUEST_URI']; $clean_uri = parse_url($request_uri, PHP_URL_PATH); $file_path = realpath($react_build_path . $clean_uri); if ($file_path && strpos($file_path, realpath($react_build_path)) === 0 && is_file($file_path)) { $mime_type = mime_content_type($file_path); header('Content-Type: ' . $mime_type); header('Content-Length: ' . filesize($file_path)); readfile($file_path); exit; } else { $index_html_path = $react_build_path . '/index.html'; if (file_exists($index_html_path)) { $content = file_get_contents($index_html_path); echo $content; } else { echo 'React app not found. Please ensure the build directory exists and contains an index.html file.'; } } ?>
.htaccess代码
<IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php [L] </IfModule> <IfModule mod_mime.c> AddType application/javascript .js AddType text/css .css AddType application/json .json </IfModule> Alias /static /home/wwwplumb/emergencyplumbersmanchester.com/build/static <Directory "/home/wwwplumb/emergencyplumbersmanchester.com/build/static"> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory>
内容的提问来源于stack exchange,提问作者dmaster
相关产品推荐
相关产品推荐

