DEV Community


Easily use multiple proxies with PAC rules

mehdipourfar profile image Mehdi Pourfar ・2 min read

I use proxies to view the contents of the websites that are blocked either for censorship reasons or by sanctions.

But using proxies all the time makes working with websites that are not blocked a little bit slower. There are also some internal websites (like for example.. bank websites) which cannot be opened with any proxy. And also for my own job, I need an ssh tunnel connection to open internal urls.

It can be really tiresome to switch between these proxies manually. After some research, I found a solution for this kind of situations: Setting up a PAC (Proxy auto-config) file.

PAC is a javascript file consisting of a function named FindProxyForUrl with .pac extension

function FindProxyForURL(url, host) {
    if (host === '') {
        return 'DIRECT';
    } else if {host === '') {
        return 'SOCKS5';
    return 'SOCKS5';

When you configure your proxy setting to use a PAC file, each time you open an address, your browser checks the url with this function to find out which proxy to use. But writing a function like this and changing it frequently can be complex and error prone.

So I decided to create a command line tool named PacGen to create this file. Here I want to show you how to work with it.

First we install it using pip:

pip install pacgen

Then we define our rules in .yml format in a file at ~/.pacgen.yml. This file consists of four segements:

  • proxies which defines our proxy servers with a name assigned to each of them.
  • routes which is a list of predefined routes for some specific hosts.
  • excludes which is list of the hosts that we want to browse without any proxy.
  • default_proxy which is the name of the default proxy for the hosts that are neither in routes nor in excludes.

Here is an example of ~/.pacgen.yml file.

  ssh_tunnel: socks5://
  shadowsocks: socks5://
routes: ssh_tunnel shadowsocks shadowsocks httpproxy shadowsocks
default_proxy: shadowsocks

After you defined your rules and saved the file, you should run the command below in your terminal.


Then it will create your PAC file in this path: ~/.proxy.pac.

Now that we have created our pac files, it's time to serve it with a webserver. The most straightforward way to do it is using nginx:

sudo apt install nginx
sudo cp ~/.proxy.pac /var/www/html/proxy.pac

Your file will be served at http://localhost/proxy.pac.
Now go to your system proxy setting and choose automatic proxy option and copy the address above into Configuration URL field. That's all.


Editor guide