React App Not Serving Static Files Correctly – MIME Type Issues

Problem:
My React app is not serving static files correctly. Requests for JavaScript and CSS files return a text/html content type instead of the expected application/javascript or text/css.

Details:

Server Details:

  • Hosting Package: Silver 100
  • Server Name: s938
  • cPanel Version: 124.0 (build 26)
  • Apache Version: 2.4.62
  • Database Version: 10.6.21-MariaDB
  • Operating System: Linux
  • IP Address:

Observations:

  1. Requests for static files (e.g., main.9b9eb604.js and main.724539ac.css) return text/html content type.
  2. Static files seem to be redirected to index.php and serve index.html.
  3. .htaccess rules appear to be causing issues with serving static files correctly.

Steps Taken:

  1. Updated .htaccess to include MIME type settings:
    <IfModule mod_mime.c>
        AddType application/javascript .js
        AddType text/css .css
        AddType application/json .json
    </IfModule>
    
  2. Ensured build directory permissions:
    chmod -R 777 /home/wwwplumb/emergencyplumbersmanchester.com/build
    
  3. Verified build output and file locations.
  4. Attempted to access static files directly, but received text/html response.

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>