Rewrite css/js paths

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-12 08:14:24

问题


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

<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 could I rewrite the paths for js/css/image files too, so when they are requested with a relative path from URL/really/nice/path/ to be served from URL/scripts/, URL/styles/ and URL/images/ folders instead? Can this be done without using RewriteBase?


回答1:


When URLs are rewritten, the client doesn't know it. So when a client looks at a page at the URL "example.com/some/url/" and the page references an image in "images/image.jpg", the client looks for the image in "example.com/some/url/images/image.jpg" even though the page actually resides in "example.com/some/other/url/". That's the problem you're facing, right?

There are three main solutions to this problem:

  1. Use absolute paths to resources instead of relative ones.
  2. Use the <base> tag to ensure that the client knows the root upon which to build its relative URLs is different from the page's apparent URL.
  3. Add a new rule for "some/url/images/" in your rewrite rules.

Option 1 is probably the best idea, and you'll find that most sites that use URL rewriting use it, including Stack Overflow itself. Option 2 is frowned upon, but works and is relatively easy. Option 3 is the most difficult to maintain, as URL rewriting exceptions and special cases can appear as you're defining new rules.

The most maintainable solution is to use absolute URLs.



来源:https://stackoverflow.com/questions/2578977/rewrite-css-js-paths

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!