where should I implement my url redirect block?

pi. asked:

I have hundreds of url redirects to implement and I am not quite certain where the best, most efficient place to implement the redirect block is:
on the varnish server or on the nginx server. The architecture is illustrated below:

enter image description here

I am inclined to implement it on the varnish server as it is the first port of call after the CDN. Please advise on weaknesses or potential issues with this. Thanks.

My answer:

Actually I think you should implement the redirects in nginx. Here is why:

Varnish can indeed create synthetic redirects, but it has to go through a lengthy chain of if comparisons for each request, which gets slower the more redirects you add. It’s O(n).

In nginx, you would create a map of old and new URLs as shown below. Because the map is stored in hash tables, lookup is much faster, about O(log n). The difference is not important with only a few redirects, but after hundreds it may get noticeable. After 57,000, it would be very slow in varnish.

In addition, varnish can now cache the redirects, instead of having to synthetically recreate them each request.

The setup in nginx looks like this: You create the map of old and new URLs, for example:

map $uri $new_uri {
    /sofa.html /living/sofas/
    /beds.html /bedroom/beds/

Then in the server block which will do the redirections, you simply add a test to see if one of the URLs matched and redirect if it did:

if ($new_uri) {
   return 301 $new_uri;

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.