【问题标题】:Routing image requests to separate subdomains将图像请求路由到单独的子域
【发布时间】:2010-11-02 15:15:24
【问题描述】:

首先,一些背景信息:

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

如果您继续阅读那篇文章,作者建议通过让多个子域都指向同一事物来“欺骗”浏览器。

如果我要从两个单独的子域(两个不同的主机名)提供我的图像,那么浏览器将最多并行下载 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" />

这需要我手动浏览相应的文件并更改每个图像的“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)

我有两个问题:

  1. 从理论上讲,这可行吗?
  2. 有没有更好的方法来完成我想要的?

【问题讨论】:

    标签: http browser image performance subdomain


    【解决方案1】:

    使用此类策略要记住的一点是,您希望将对同一文件的请求定向到同一服务器。请求以下内容并没有多大用处:

    http://subdomain1.example.com/img1.jpg
    http://subdomain2.example.com/img2.jpg
    http://subdomain1.example.com/img3.jpg
    http://subdomain2.example.com/img4.jpg
    

    然后在一页上:

    http://subdomain2.example.com/img1.jpg
    http://subdomain1.example.com/img2.jpg
    http://subdomain2.example.com/img3.jpg
    http://subdomain1.example.com/img4.jpg
    

    在下一个。

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

    var serverNumber = image.GetHashCode() % serverCount;
    

    这确保了对同一图像的进一步请求是从浏览器的缓存而不是由不同的服务器提供的。

    【讨论】:

      【解决方案2】:

      您最好将所有图像都放在一台服务器上,而不是对每个图像进行 2 个请求。

      如果您有动态页面内容(即看起来您正在使用 php),您可以通过创建一个执行相同操作的函数来获得相同的效果并直接在 html 中对子域进行编码。您的图片标签可能如下所示:

      <img src="<?php echo image_root(); ?>/dir/image.jpg">
      

      您应该能够通过一个不错的编辑器和一些正则表达式搜索和替换将这种更改全局应用于您的网站。

      【讨论】:

        【解决方案3】:
        1. 是的。它会起作用的。但是您最终会收到两倍的请求,但仍然会阻碍第一个请求以通过二乘二主域获得可能的重定向。

        2. 您可以尝试在图像实际开始加载之前使用 JavaScript(也称为 jQuery)在 DOM 的就绪事件中快速更改图像的来源。您希望使用一致的方法来计算要使用的子域选项,以便将来引用相同图像的页面会导致对相同子域选择的更改。

        【讨论】:

          猜你喜欢
          • 2020-04-16
          • 1970-01-01
          • 2013-06-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-04-03
          • 1970-01-01
          相关资源
          最近更新 更多