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

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

Susan Sarandon
Release: 2024-12-02 09:37:10
Original
617 people have browsed it

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

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

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 tag within the element of your pages:

<base href="/detail/123/">
Copy after login

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!

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