Home >Backend Development >PHP Tutorial >How to Fix Broken CSS, JavaScript, and Images After Implementing SEO-Friendly URLs?

How to Fix Broken CSS, JavaScript, and Images After Implementing SEO-Friendly URLs?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-27 22:23:11743browse

How to Fix Broken CSS, JavaScript, and Images After Implementing SEO-Friendly URLs?

Troubleshooting Broken CSS, JavaScript, and Images with SEO-Friendly URLs

When implementing SEO-friendly URLs through .htaccess rewrites, it's common to encounter issues with CSS, JavaScript, and images failing to load. This is due to the base URI of these assets being modified after the URL rewrite.

To illustrate the issue, consider the following rewrite rule:

RewriteRule ^swift-details/([0-9]+)/([0-9a-zA-Z_-]+)$ swift-details.php?id= [NC,L]
RewriteRule ^swift-details/(css|js|img)/(.*)?$ // [L,QSA,R=301]

This rule successfully routes requests to the desired location, but the relative URIs within the HTML no longer function correctly. For example, in the original URL structure, the base URI for assets would be "/". However, after the rewrite, the base becomes "/swift/details/". As a result, the browser attempts to prepend this base to all relative URLs, resulting in broken references.

To resolve this issue, two options are available:

  1. Use Absolute Links: Modify the HTML to use absolute URLs for CSS, JavaScript, and images. This approach ensures that the references remain consistent regardless of the base URI.
  2. Set the URI Base: Within the HTML head section, add the following line:
<base href="/" />

This sets the base URI to "/" for all pages, ensuring that relative URIs are resolved correctly by the browser, even after the URL rewrite.

The above is the detailed content of How to Fix Broken CSS, JavaScript, and Images After Implementing SEO-Friendly URLs?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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