Home > Backend Development > PHP Tutorial > How to Prevent CSS, JS, and Image Loading Issues After URL Rewriting?

How to Prevent CSS, JS, and Image Loading Issues After URL Rewriting?

Linda Hamilton
Release: 2024-12-02 19:09:15
Original
240 people have browsed it

How to Prevent CSS, JS, and Image Loading Issues After URL Rewriting?

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=
Copy after login

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 /
Copy after login

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=
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template