Codementor Events

NginScript : upstream randomizer

Published Jul 10, 2018
NginScript : upstream randomizer

Preface

Few months ago I created Nginx set up which redirected every single request to random proxy from a list. This feature has been implemented purely inside nginx config with javascript plugin. Let me show you how to get started with NginxScript itself and implement simple function like randomizer inside config. This set up has been installed on Ubuntu 16.04

Installing nginx & nginScript

Step 1

sudo apt-get update
wget http://nginx.org/keys/nginx_signing.key
sudo apt-key add nginx_signing.key

Step 2

Add to end of the file /etc/apt/sources.list

deb http://nginx.org/packages/ubuntu/ xenial nginx
deb-src http://nginx.org/packages/ubuntu/ xenial nginx

Step 3

sudo apt-get update
sudo apt-get install nginx
sudo apt-get install nginx-module-njs

Installation process is complete.

Configuration set up

Step 1

Create script.js file inside /etc/nginx/ folder
And put this code inside of it.

var list = [
  "201.140.132.34:8080",
  "50.233.137.34:80",
  "204.52.206.65:8080",
  "75.114.77.38:8080",
  "50.233.137.33:80",
  "52.8.41.246:3128",
  "198.50.168.210:80",
  "173.192.21.89:80",
  "75.114.77.35:8080",
  "206.81.5.117:8080"
]

function random(){
    var index = Math.floor(list.length * Math.random());
    return list[index];
}

Step 2
Now let modify /etc/nginx/nginx.conf
Put the following code there.

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


load_module modules/ngx_http_js_module.so;
load_module modules/ngx_stream_js_module.so;


events {
    worker_connections  1024;
}

stream {


        js_include  script.js;

        js_set $proxy random;


        server {
            listen 53;
            proxy_responses 1;
            proxy_timeout 20s;
            proxy_pass $proxy;
        }
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;



    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;
    #
    #include /etc/nginx/conf.d/*.conf;
}

Basically that's it. All done.
Just run this command:

sudo service nginx restart

And latest changes will be applied.

NOTE!

I took a list of public proxies. But they are not super stable. That's why I needed to monitor each of them frequently and update a list of available ones.
It's been implemented with python and bash script.

If anybody need smth like this, just ping me in private message.

Alex Polymath

Discover and read more posts from Alex Polymath
get started