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

前端 未结 2 1482
陌清茗
陌清茗 2021-02-04 20:52

I am using .htaccess to accelerate a site with the following redirects:

request for http://example.com/images/name.jpg  routed to  http://i.example.com/name.jpg
r         


        
相关标签:
2条回答
  • 2021-02-04 21:23

    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.

    0 讨论(0)
  • 2021-02-04 21:30

    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.

    0 讨论(0)
提交回复
热议问题