我有一个映射的 htaccess 文件
http://www.myserver.com/home/to
http://www.myserver.com/index.php?section=home
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/etc.
After redirection the browser will look for the files under
http://www.myserver.com/home/assets/images/which causes things to break, as this is not a valid path.
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/
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/
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 路径如 assets/images/
在具有 URI 路径 /home/
的 HTML 文档中解析为/home/assets/images/
而不是/assets/images/
.
您无法使用 mod_rewrite 更改此设置,因为 URI 解析是由客户端而非服务器完成的。唯一的解决方案是:
- 使用
BASE
element 更改基本 URI (请注意,这会影响所有相对URI); - 使用绝对 URI 路径,例如
/assets/images/
而不是亲戚assets/images/
; - 调整相对URI路径,因此引用
/home/
调整为../assets/images/
反射(reflect)路径深度。
关于.htaccess - htaccess 重写会破坏相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18284652/