site 5x faster via mod_rewrite, but CSS images are broken

不问归期 提交于 2019-12-03 00:45:48

I was able to resolve this by not trying to incorporate directories into the subdomains:

request for domain.com/images/  routed to  i.domain.com/images/
request for domain.com/css/     routed to  c.domain.com/css/

It works perfectly and is still extremely fast.

There seems to be a bug in modern browsers where a css request that is redirected will apply only the new domain, leaving the original directories as part of the request:

If a css image at url(domain.com/images/name.jpg) is redirected to i.domain.com/name.jpg, the browser will mistakenly request i.domain.com/images/name.jpg.

I found a way to solve this problem if all host names use the same virtual host:

# redirect externally if path doesn’t match host name
RewriteCond %{HTTP_HOST} !^i\.example\.com$
RewriteRule ^images/([^/]+)$ http://i.example.com/$1 [L,R=301]
RewriteCond %{HTTP_HOST} !^c\.example\.com$
RewriteRule ^css/([^/]+)$ http://c.example.com/$1 [L,R=301]

# redirect internally to the file
RewriteCond %{HTTP_HOST} ^i\.example\.com$
RewriteRule !^images/ images%{REQUEST_URI} [L]
RewriteCond %{HTTP_HOST} ^c\.example\.com$
RewriteRule !^css/ css%{REQUEST_URI} [L]

This will do the following:

http://example.com/css/foo       externally to    http://c.example.com/foo
http://c.example.com/foo         internally to    /css/foo

http://example.com/images/bar    externally to    http://i.example.com/bar
http://i.example.com/bar         internally to    /images/bar

As well as correcting mismatching paths and host names:

http://i.example.com/css/foo     externally to    http://c.example.com/foo
http://c.example.com/images/bar  externally to    http://i.example.com/bar

A mismatch occurs when the requested stylesheet http://example.com/css/foo is redirected to http://c.example.com/foo and an image URI reference like /images/bar inside the stylesheet is resolved from this new base URI and thus leading to http://c.example.com/images/bar instead of the initial http://example.com/images/bar.

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