Romans Ruskovs
Romans Ruskovs

Reputation: 197

Redirect request to CDN using nginx

I have a couple of server addreses, like cdn1.website.com, cdn2.website.com, cdn3.website.com. Each of them holds simillar files.

Request comes to my server and I want to redirect or rewrite it to a random cdn server. Is it possible ?

Upvotes: 7

Views: 7586

Answers (2)

kolbyjack
kolbyjack

Reputation: 18300

You could try using the split clients module:

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;
    }
  }
}

Upvotes: 8

halfdan
halfdan

Reputation: 34244

This is of course possible. Nginx comes with load balancing:

upstream  mysite  {
   server   www1.mysite.com;
   server   www2.mysite.com;
}

This defines 2 servers for load balancing. By default requests will be equally distributed across all defined servers. You can however add weights to the server entries.

Inside your server {} configuration you can now add the following to pass incoming requests to the load balancer (e.g. to load balance all requests for the images directory):

location /images/ {
      proxy_pass  http://mysite;
}

Have a look at the documentation for a more detailed description.

Upvotes: 0

Related Questions