重写 css/js 路径

发布于 2024-08-28 02:34:10 字数 524 浏览 1 评论 0原文

所以我将我的路径重写为: URL/really/nice/paths/ 使用这样的 mod_rewrite 规则:

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

问题是我如何也重写 js/css/image 文件的路径,所以当它们被请求带有相对路径,来自 URL/really/nice/path/,以便从 URL/scripts/URL 提供服务/styles/URL/images/ 文件夹?可以在不使用RewriteBase的情况下完成此操作吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅浅淡淡 2024-09-04 02:34:10

当 URL 被重写时,客户端并不知道。因此,当客户端查看 URL“example.com/some/url/”的页面并且该页面引用“images/image.jpg”中的图像时,客户端会在“example.com/some/”中查找该图像。 url/images/image.jpg”,即使该页面实际上位于“example.com/some/other/url/”。这就是你面临的问题,对吧?

此问题的解决方案主要有以下三种:

  1. 使用资源的绝对路径而不是相对路径。
  2. 使用 标记来确保客户端知道构建其相对 URL 的根与页面的明显 URL 不同。
  3. 在重写规则中添加“some/url/images/”的新规则。

选项 1 可能是最好的主意,您会发现大多数使用 URL 重写的网站都使用它,包括 Stack Overflow 本身。选项 2 不受欢迎,但有效且相对简单。选项 3 是最难维护的,因为在定义新规则时可能会出现 URL 重写异常和特殊情况。

最可维护的解决方案是使用绝对 URL。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文