Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to direct to a randomly selected entry from a list in Nginx is by using the Nginx "map" module along with the "rand" function.

Here are the steps to do that:

  1. First, define a variable with the list of entries that you want to randomly select from. For example:
map $random_variable $selected_entry {
  default "example.com/entry1";
  1 "example.com/entry2";
  2 "example.com/entry3";
  3 "example.com/entry4";
}

Here, we are defining a map called "$selectedentry" that will take a random value from the variable "$randomvariable" and return a corresponding entry from the list.

The "default" value is the entry that will be returned if none of the other values match. In this example, we have four entries in the list, but you can add or remove entries as needed.

  1. Next, use the "rand" function to generate a random number between 0 and the maximum number of entries in your list. For example:
set $random_variable rand(0,3);

Here, we are setting the "$random_variable" variable to a random number between 0 and 3 (since we have 4 entries in our list).

  1. Finally, use the "$selected_entry" variable to redirect the request to the randomly selected entry. For example:
rewrite ^/random-entry$ $selected_entry redirect;

Here, we are redirecting any request to "/random-entry" to the randomly selected entry using the "$selected_entry" variable.

Note: You can customize the variable names and values as per your requirements.