URL Rewriting: Resolving Loading Issues for CSS, JS, and Images
In URL rewriting, it's common to encounter scenarios where CSS, JS, and image files stop loading after redirection. This issue typically occurs when relative paths are used and the redirection rule modifies the base URL.
To illustrate, consider the following configuration:
Options +FollowSymLinks RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteRule ^detail/([0-9]+)/?$ detail.php?id=
In this case, the rule redirects URLs like "http://localhost/detail/123" to "http://localhost/detail.php?id=123". While the redirection occurs successfully, CSS, JS, and image files located in "http://localhost/css/" and "http://localhost/js/" fail to load because the relative paths are no longer valid.
Addressing the Issue
One commonly proposed solution involves changing the relative paths to absolute paths, such as "/css/" and "/js/". However, this approach requires manual edits to multiple files and is not considered a reliable solution.
Alternative Solution Using .htaccess Rules
To address this issue while preserving relative paths, consider the following solution:
Insert the following line in your .htaccess file before the RewriteRule statement:
RewriteBase /
This ensures that the base URI remains "/" even after redirection, resolving the issue with relative paths.
Example:
With the above modification, the .htaccess file now appears as follows:
Options +FollowSymLinks RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteRule ^detail/([0-9]+)/?$ detail.php?id=
Note: Remember to place the "RewriteBase /" line before any RewriteRule statements.
The above is the detailed content of How to Prevent CSS, JS, and Image Loading Issues After URL Rewriting?. For more information, please follow other related articles on the PHP Chinese website!