Nginx Reverse Proxies – Saves you from Bad DNS

Nginx is considered a webserver, but its a lot more than that. Its can be used as a reverse proxy. In this article, we cover two use case scenarios:

  • Internal Reverse Proxy for Applications
  • External Reverse Proxy to compensate for bad DNS/TTL

 

What is a reverse proxy?

Let me give you an example:
You get traffic to NGINX on port 80 (HTTP), but your Node.JS application is running on port 3000? You can use the reverse proxy to route your port 80 HTTP request to port 3000.

Here’s how you might configure such a scenario:

server {   listen       80;   server_name  localhost; # could be your_site.com     location / {     proxy_pass http://localhost:3000;     proxy_http_version 1.1;     proxy_set_header Upgrade $http_upgrade;     proxy_set_header Connection 'upgrade';     proxy_set_header Host $host;     proxy_cache_bypass $http_upgrade;   }   }

 

A Unique Use Case I (unfortunately) Came Across — Bad DNS

At one point last year, I had to reroute HTTP traffic due to a DNS delay from one IP to another. With NGINX, you can easily reverse proxy the packets to another server.

Here’s a diagram of what I’m talking about:

NGINX Reverse Proxy diagram

Since the slower DNS is pointing to the older box’s IP address, we can use NGINX as a way to reroute HTTP traffic from the old box to the new box. This will be seamless to the user if done correctly.

Here’s how you might configure against this situation:

server {   listen old_box_ip;   server_name yoursite.com;   location / {     proxy_pass  http://new_box_ip;     proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;     proxy_redirect off;     proxy_buffering off;     proxy_set_header        Host            static.example.com;     proxy_set_header        X-Real-IP       $remote_addr;     proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;   } }

 

By rerouting the HTTP packets from one IP to another, the DNS delay was not experienced by the end user.

Also, if you’re looking to redirect SSL (443) traffic, you can check out this Digital Ocean link