How to configure Nginx server to connect to multiple websites using reverse proxy

1. In order to make your Nginx server to allow reverse proxy to your web app, edit
/etc/nginx/sites-available as follows:

 # =========== server 1 www.a.com ==============

# nodejs

upstream rails {

  server localhost:3000; # 

}


server {

  listen 80 default;

  server_name www.a.com;

# You can write server name in sequence:

#  server_name www.a.com, www.a.org; # OR IP ADDRESS

#  or one by one;

#  www.a.com;

#  www.a.org;


  location / {

    proxy_pass http://rails;

  }

}

# =========== server 2 www.b.com ==============

# for example if you want to redirect to port 8080

server {

  listen 80;

  server_name www.b.com;


  location / {

   proxy_pass http://localhost:8080;

   proxy_set_header origin 'http://localhost:8080';

  }

}

2. If currently you don't have real domain: www.a.com , www.b.com and you are testing local environment only, then edit /etc/hosts as follows:
127.0.0.1   localhost
127.0.0.1   www.a.com
127.0.0.1   www.b.com
127.0.0.1   www.c.com


3. If you want to make it work for Ruby on Rails, then edit on Ruby on Rails app's /config/initializers/cors.rb .
Rails.application.config.middleware.insert_before 0, Rack::Cors do
# ===== DEFAULT =====
# allow do
# origins '*'
# resource '*', headers: :any, methods: [:get, :post, :patch, :put]
# end

# ==== LIMITED =====
allow do
origins 'localhost:8080'
resource '/annexes',
:headers => :any,
:methods => [:post]
resource '/inquiries',
headers: :any,
methods: [:get, :post, :put]
end
end

Comments