Rewrite css / js paths

So, I rewrote my paths to something like: URL/really/nice/paths/ using mod_rewrite rules such as:

 <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?url=$1 [PT,L] </IfModule> 

The question is how can I rewrite the paths for js / css / image files, so when they are requested with a relative path from URL/really/nice/path/ for service from URL/scripts/ , URL/styles/ and URL/images/ instead of them? Can this be done without using RewriteBase ?

+4
source share
1 answer

When URLs are rewritten, the client does not know this. Therefore, when a client views the page at the URL "example.com/some/url/" and the page refers to the image in "images / image.jpg", the client searches for the image in "example.com/some/url/images/image. jpg ", although the page is indeed located in" example.com/some/other/url/ ". What is the problem you are facing, right?

There are three main solutions to this problem:

  • Use absolute resource paths instead of relative ones.
  • Use the <base> tag to make sure that the client knows the root directory in which it creates its relative URLs, different from the display URL of the page.
  • Add a new rule for "some / url / images /" in the rewrite rules.

Option 1 is probably the best idea, and you will find that most sites using URL rewriting use it, including the stack overflow itself. Option 2 frowned, but it works and is relatively simple. Option 3 is the most difficult to maintain, as URL rewriting exceptions and special cases may appear as you define new rules.

The most convenient solution is to use absolute URLs.

+11
source

Source: https://habr.com/ru/post/1306031/


All Articles