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

前端 未结 2 1484
陌清茗
陌清茗 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: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.

提交回复
热议问题