Lewati ke isi

NGINX reverse proxy

What is a Reverse Proxy?

A reverse proxy is a server that sits between internal applications and external clients, forwarding client requests to the appropriate server. While many common applications, such as Node.js, are able to function as servers on their own, NGINX has a number of advanced load balancing, security, and acceleration features that most specialized applications lack. Using NGINX as a reverse proxy enables you to add these features to any application.

This guide uses a simple Node.js app to demonstrate how to configure NGINX as a reverse proxy.

What Are The Benefits Of A Reverse Proxy?

Reverse proxy servers are able to support a number of use-cases. Some of the benefits of using a reverse proxy include:

  1. SSL Offloading or inspection
  2. Server load balancing
  3. Port forwarding
  4. Caching
  5. L7 filtering and routing

Install NGINX

sudo apt update
sudo apt install nginx

Ensure NGINX is running and enabled to start automatically on reboot:

sudo systemctl start nginx
sudo systemctl enable nginx

Create an Example App

python3 -m http.server 8080

test python http server

http://127.0.0.1:8080/

atau

curl localhost:8080/

Configure NGINX

At this point, you could configure Node.js to serve the example app on your public IP address, which would expose the app to the internet. Instead, this section configures NGINX to forward all requests from the public IP address to the server already listening on localhost.

Basic Configuration for an NGINX Reverse Proxy

  1. Create a configuration file for the app in /etc/nginx/conf.d/. Replace example.com in this example with your app’s domain or public IP address:
sudo nano /etc/nginx/conf.d/pythonapp.conf

tambahkan konfigurasi di bawah ini

server {
  listen 80;
  listen [::]:80;

  server_name example.com;

  location / {
      proxy_pass http://localhost:8080/;
  }
}

The proxy_pass directive is what makes this configuration a reverse proxy. It specifies that all requests which match the location block (in this case the root / path) should be forwarded to port 3000 on localhost, where the Node.js app is running.

  1. Disable or delete the default Welcome to NGINX page:
sudo mv /etc/nginx/conf.d/default.conf /etc/nginx/conf.d/default.conf.disabled
  1. Test the configuration:
sudo nginx -t
  1. If no errors are reported, reload the new configuration:
sudo nginx -s reload
  1. In a browser, navigate to your public IP address (local). You should see the “Hello World!” message displayed.