使用nginx将请求重定向到CDN

Rom*_*ovs 7 proxy rewrite cdn nginx

我有几个服务器地址,如cdn1.website.com,cdn2.website.com,cdn3.website.com.他们每个人都持有simillar文件.

请求来到我的服务器,我想将其重定向或重写为随机的cdn服务器.可能吗 ?

kol*_*ack 7

您可以尝试使用拆分客户端模块:

http {

  # Split clients (approximately) equally based on
  # client ip address
  split_clients $remote_addr $cdn_host {
    33% cdn1;
    33% cdn2;
    - cdn3;
  }

  server {
    server_name example.com;

    # Use the variable defined by the split_clients block to determine
    # the rewritten hostname for requests beginning with /images/
    location /images/ {
      rewrite ^ http://$cdn_host.example.com$request_uri? permanent;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是问题的正确解决方案,但它并不是我希望你真正想要的最佳方式.具体来说,您正试图从Web服务器卸载工作.如果您的应用程序首先向您的Web服务器发送CDN请求,然后重定向,您实际上并没有将所有内容卸载到CDN.理想情况下,您希望应用程序本身直接呈现CDN上的资产链接.如果使用Rails,则可以使用内置的"资产主机"功能.其他框架有类似的功能,你可以DIY :) (3认同)