Last Updated: February 25, 2016
·
3.497K
· vaneyckt

Creating your first Nginx reverse proxy config

Reverse proxies are a great way to enable access to multiple websites running on different web servers on the same machine.

Imagine you have the following:

  • a local rails web server listening on port 3000 that serves the www.railsies.com site
  • a local django web server on port 4000 that serves the www.djangogo.com site

Now when your machine receives a http request, you'll want it to be forwarded internally to either port 3000 or 4000 depending on the url specified. This is exactly what a reverse proxy does!

We'll use nginx to setup our reverse proxy.

# install nginx
sudo apt-get install nginx

# remove default configuration
sudo rm /etc/nginx/sites-available/default
sudo rm /etc/nginx/sites-enabled/default

# create a config file for each webserver
sudo touch /etc/nginx/sites-available/railsies
sudo touch /etc/nginx/sites-available/djangogo

# add symlinks for our config files
sudo ln -s /etc/nginx/sites-available/railsies /etc/nginx/sites-enabled/railsies
sudo ln -s /etc/nginx/sites-available/djangogo /etc/nginx/sites-enabled/djangogo

# set railsies config
sudo cat /etc/nginx/sites-available/railsies >
upstream railsies {
  server 127.0.0.1:3000;
}

server {
  listen 80;
  server_name www.railsies.com;

  location / {
    proxy_pass              http://railsies;
    proxy_set_header        Host $host;
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_connect_timeout   150;
    proxy_send_timeout      100;
    proxy_read_timeout      100;
    proxy_buffers           4 32k;
    client_max_body_size    8m;
    client_body_buffer_size 128k;
  }
}
^D # Hit CTRL + D to finish writing the file

# set djangogo config
sudo cat /etc/nginx/sites-available/djangogo >
upstream djangogo {
  server 127.0.0.1:4000;
}

server {
  listen 80;
  server_name www.djangogo.com;

  location / {
    proxy_pass              http://djangogo;
    proxy_set_header        Host $host;
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_connect_timeout   150;
    proxy_send_timeout      100;
    proxy_read_timeout      100;
    proxy_buffers           4 32k;
    client_max_body_size    8m;
    client_body_buffer_size 128k;
  }
}
^D # Hit CTRL + D to finish writing the file

# reload configs
sudo service nginx reload

That should do it. Any requests for www.railsies.com will now be forwarded to port 3000, while those for www.djangogo.com will be sent on to port 4000.