Home >Backend Development >PHP Tutorial >Why Are My CSS, JS, and Images Broken After Implementing SEO-Friendly URLs?

Why Are My CSS, JS, and Images Broken After Implementing SEO-Friendly URLs?

DDD
DDDOriginal
2024-12-25 12:42:20729browse

Why Are My CSS, JS, and Images Broken After Implementing SEO-Friendly URLs?

SEO-Friendly URLs Impact CSS, JS, and Image Functionality: A Rewriting Strategy

To enhance search engine optimization (SEO), you have rewritten your .htaccess file with the intention of implementing SEO-friendly URLs. However, you have encountered an unexpected issue: CSS, JS, and images are not functioning as expected on the modified pages.

The issue arises from the fact that your original .htaccess file configuration creates SEO-friendly URLs using the following rules:

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]

The first rule rewrites the URL into a more SEO-friendly format. The issue lies in the second rule. it attempts to map requests for CSS, JS, and images to their absolute counterparts while maintaining relative links within your pages.

However, this approach alters the base URI of your pages, causing relative links (such as "styles.css") to fail because the browser now interprets them relative to the modified URL (e.g., "/swift-details/2/abblinbb"). As a result, CSS, JS, and images are not loaded correctly.

Fix: Absolute or Base URI Injection

There are two possible solutions to resolve this issue:

  • Use Absolute Links: Modify the links within your pages to use absolute URLs instead of relative ones (e.g., "/css/styles.css").
  • Infect the Base URI: Add a tag with an absolute base URI within the section of your pages:
<head>
  <base href="/" />
</head>

This will force the browser to resolve relative links with the appropriate base URI, ensuring CSS, JS, and images load as expected.

The above is the detailed content of Why Are My CSS, JS, and Images Broken 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