htaccess 重写破坏了相对路径 [英] htaccess rewrite breaks relative paths
问题描述
我有一个将
http://www.myserver.com/home/
映射到
http://www.myserver.com/index.php?section=home
这部分工作正常.我现在面临的问题是,我所有的图像和 css 都位于一个名为 assets 的子文件夹中,即
This part works fine. The issue I am facing now is, all my images and css reside in a sub-folder named assets, i.e.
http://www.myserver.com/assets/images/
http://www.myserver.com/assets/css/
等
重定向后浏览器会在
http://www.myserver.com/home/assets/images/
下寻找文件这会导致事情中断,因为这不是一条有效的路径.
which causes things to break, as this is not a valid path.
我已经能够添加另一个重写,将上述内容映射到正确的子文件夹,但是,Firebug 显示图像驻留在:
I have been able to add another rewrite that maps the above to the correct sub-folder, however, Firebug shows that the images are residing in:
http://www.myserver.com/home/assets/images/
我知道这不是真正的问题,毕竟,我的图像和 css 使用此规则加载得很好.我只是很好奇如何使路径显示为实际路径,即:
I know it's not really a problem, after all, my images and css are loading just fine with this rule. I'm just curious as to how I could make the path shown to be the actual path, which is:
http://www.myserver.com/assets/images/
在下面粘贴我的 htaccess 文件.事先非常感谢.
Pasting my htaccess file below. Thank you very much beforehand.
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^([^/]+)/assets/(css|images|js)/(.*)$ /assets/$2/$3 [NC,L]
RewriteRule ^([^/]+)/$ /index.php?section=$1 [NC,L]
推荐答案
问题是你没有考虑到相对 URL 是在基本 URI 上解析的,基本 URI 是使用引用的 HTML 文档的 URI.所以具有 URI 路径 /home/
的 HTML 文档中的相对 URI 路径(如 assets/images/
被解析为 /home/assets/images/
> 而不是 /assets/images/
.
The problem is that you didn’t consider that relative URLs are resolved on the base URI that is the URI of the HTML document the reference is used in. So a relative URI path like assets/images/
in an HTML document with the URI path /home/
is resolved to /home/assets/images/
instead of /assets/images/
.
您不能使用 mod_rewrite 更改此设置,因为 URI 解析是由客户端完成的,而不是由服务器完成的.唯一的解决办法是:
You cannot change this with mod_rewrite as URI resolution is done by the client and not by the server. The only solutions are:
- 使用
BASE代码>元素
(注意这会影响所有相对URI); - 使用绝对 URI 路径,例如
/assets/images/
而不是相对的assets/images/
; - 调整相对 URI 路径,因此将
/home/
中的引用调整为../assets/images/
以反映路径深度.
- change the base URI using the
BASE
element (note that this affects all relative URI); - using absolute URI paths, e.g.
/assets/images/
instead of a relativeassets/images/
; - adjusting the relative URI path, so references in
/home/
are adjusted to../assets/images/
to reflect the path depth.
这篇关于htaccess 重写破坏了相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!