URL Rewriting: Resolving Failed Loading of CSS, JS, and Images
When implementing URL rewriting rules in .htaccess, a common issue arises where external assets such as CSS, JS, and images fail to load correctly. This can be attributed to the change in URI base when the redirection occurs.
An initial solution involves using absolute paths, which ensures the assets are located regardless of the page's URL. However, this requires tedious modifications to all files, rendering it an unreliable solution.
An alternative approach leverages .htaccess rules to establish a consistent base URI:
RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteRule ^detail/([0-9]+)/?$ detail.php?id= RewriteEngine On RewriteCond %{REQUEST_URI} !^/css/ RewriteCond %{REQUEST_URI} !^/js/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /detail/123/ [R=307,L]
This rule ensures that all external assets are referenced from the /detail/123/ URL. The [R=307,L] flag redirects the request to the correct base URI (/detail/123/), effectively solving the asset loading issue without requiring absolute paths.
In conjunction with this, you can add a
<base href="/detail/123/">
This further solidifies the base URI and enables relative paths to function correctly. By implementing these rules, you can maintain URL rewriting while avoiding the need to edit individual files, ensuring a seamless user experience.
The above is the detailed content of How to Fix CSS, JS, and Image Loading Issues After Implementing URL Rewriting?. For more information, please follow other related articles on the PHP Chinese website!