将图像请求路由到单独的子域

Jam*_*mes 2 browser subdomain performance image http

首先,一些背景信息:

大约1999年的HTTP 1.1规范建议浏览器和服务器将对同一主机名的并行请求限制为两个.(更多)

如果你继续阅读那篇文章作者建议"愚弄"浏览器,让多个子域名都指向同一个东西.

如果我要从两个单独的子域(两个不同的主机名)提供我的图像,那么浏览器将并行下载最多4个图像(每个主机名2个).

鉴于此,我现在可以在两个子域之间平均分配请求以优化页面下载速度,如下所示:

<img src="http://subdomain1.example.com/img1.jpg" />
<img src="http://subdomain2.example.com/img2.jpg" />
<img src="http://subdomain1.example.com/img3.jpg" />
<img src="http://subdomain2.example.com/img4.jpg" />
Run Code Online (Sandbox Code Playgroud)

这需要我手动浏览相应的文件并更改每个图像的'src'.


我正在寻找一个更简单/可重用的解决方案,它不会对HTML进行任何可见的更改.

我有个主意:

  1. [example.com]上的所有类似图像的URL都被重定向(通过.htaccess)到[example.com/imghandler.php]
  2. imghandler.php重定向到subdomain1或subdomain2 - 随机选择.

为了显示:

# Request from browser:
>> http://example.com/dir/image.jpg

# Rewritten to:
>> http://example.com/imghandler.php?location=%2Fdir%2Fimage.jpg

# *Redirects* to either:
    1:
        >> http://subdomain1.example.com/dir/image.jpg
           (this is where the browser ends up getting the image from)
    2:
        >> http://subdomain2.example.com/dir/image.jpg
           (this is where the browser ends up getting the image from)
Run Code Online (Sandbox Code Playgroud)

我有两个问题:

  1. 从理论的角度来看,这会有用吗?
  2. 有没有更好的方法来实现我想要的东西?

Tal*_*joe 5

要记住这样的策略,有一点需要将同一文件的请求定向到同一服务器.要求:没有多大帮助:

http://subdomain1.example.com/img1.jpg
http://subdomain2.example.com/img2.jpg
http://subdomain1.example.com/img3.jpg
http://subdomain2.example.com/img4.jpg
Run Code Online (Sandbox Code Playgroud)

然后在一页上:

http://subdomain2.example.com/img1.jpg
http://subdomain1.example.com/img2.jpg
http://subdomain2.example.com/img3.jpg
http://subdomain1.example.com/img4.jpg
Run Code Online (Sandbox Code Playgroud)

在下一个.

我们在这里使用的技巧是散列文件名(C#中的GetHashCode)并使用它来选择存储桶:

var serverNumber = image.GetHashCode() % serverCount;
Run Code Online (Sandbox Code Playgroud)

这可确保从浏览器的缓存中提供对同一图像的进一步请求,而不是由其他服务器提供.