.htaccess - htaccess 重写会破坏相对路径

标签 .htaccess mod-rewrite url-rewriting

我有一个映射的 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/

相关文章:

php - 如何在 .htaccess 中将路径附加到 PHP include_path

.htaccess - 当我将它设置为来自另一个主机的网站的子域时,不保护子域 heroku 网站

.htaccess - 交响乐2 : How to remove the "/web/" folder from the url in a shared hosting?

magento - Magento 怎么可能只为该类别的产品创建 SEO 链接

apache - 在 SEO 方面绕过子域与子文件夹的方法?

apache - .htaccess 在不是 www 时强制 ssl

.htaccess - 使用.htaccess从不同文件夹加载文件

php - 带有 .htaccess 的漂亮 URL

url - mod_rewrite 和 "pretty urls"

.htaccess - 在 Laravel 5 项目上应用 SSL 后所有路由上的 404