nginx redirect to varios directories

user1908375 asked:

I am looking for a way redirect the URLrequest to various directories.

For example the user calls server.com/get.php

I want it randomly be redirected to server.com/a/get.php, or server.com/b/get.php or server.com/c/get.php etc.

I know there is a way to use

upstream myapp1 {
        server srv1.example.com weight=3;
        server srv2.example.com;
        server srv3.example.com;
    }

for redirecting requests to various servers. But could I do the same with directories?

Updated:
should it be this?:

location ~ .php$ {
        try_files $variant$uri $variant$uri/ $variant/index.php;
        root           /usr/share/nginx/html;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME   $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }

Regards

My answer:


You could do this more easily with nginx’s split clients module.

For instance, if you want a roughly three way split:

http {
    split_clients "${remote_addr}AAA" $variant {
        33%     "/a";
        33%     "/b";
        *       "/c";
    }

Then in your server block, replace:

    try_files $uri $uri/ /index.php;

with:

    try_files $variant$uri $variant$uri/ $variant/index.php;

View the full question and answer on Server Fault.

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