Rare features nginx: random_index

    I decided to make my dream come true, and write about some nginx modules, which are rarely used. Today we will talk about random_index_module.


    Suppose you want the user to receive slightly different content each time he visits the same page, randomly. Well, for example, your software has a bunch of awards from several software publications that you really want to demonstrate to the user, but at the same time, the place in the page design is allocated only for one picture. Or do you want to create a mini-banner system within the same site with a random distribution of banners. :) There can be many applications.

    The easiest option is to make several static versions of the page and include the appropriate directive in the config.

    location /index.html {
    random_index on;
    alias /www/root/random_pages/;
    }

    Thus, every time someone requests /index.html from you, nginx will access the directory / www / root / random_pages and give one of the files that it finds there randomly.

    However, there are a number of problems - if there are several “blinking” blocks, the number of page options can increase very quickly.

    There is a solution if you recall the SSI. We describe a separate location for each set of our random blocks, for example: And in the only (this time) index.html page we write: And all you have to do is put in the directories / www / root / banners / and / www / root / awards / a few (or at least one) file with the corresponding html content.

    location /banners/ {
    random_index on;
    alias /www/root/banners/;
    }

    location /awards/ {
    random_index on;
    alias /www/root/awards/;
    }




    ...






    Of course, this scheme can be further improved by adding error handling (if you still forgot to put at least one file in the above folders), but this can be left “for homework”. :)

    Also popular now: