A universal nginx interface to implement reverse proxy configuration

A universal nginx interface to implement reverse proxy configuration

1. What is a proxy server?

Proxy server, when the client sends a request, it will not send it directly to the destination host, but first send it to the proxy server. After the proxy service accepts the client's request, it will send it to the host and receive the data returned by the destination host, store it in the hard disk of the proxy server, and then send it to the client.

2. Why use a proxy server?

1) Improve access speed

Since the data returned by the target host will be stored in the hard disk of the proxy server, the next time the client accesses the same site data, it will be read directly from the hard disk of the proxy server, which plays a caching role. Especially for popular sites, it can significantly improve the request speed.

2) Firewall function

Because all client requests must go through the proxy server to access the remote site, you can set limits on the proxy server to filter certain unsafe information.

3) Access inaccessible target sites through proxy servers

There are many proxy servers developed on the Internet. When the client's access is restricted, it can access the target site through an unrestricted proxy server. In layman's terms, the browser we use to bypass the firewall utilizes the proxy server. Although we cannot go abroad, we can also directly access the external network.

Reverse Proxy vs Forward Proxy

1. What is a forward proxy? What is a reverse proxy?

A forward proxy is set up between the client and the target host and is only used to proxy the connection requests from the internal network to the Internet. The client must specify a proxy server and send the http requests that were originally sent directly to the Web server to the proxy server.

The reverse proxy server is set up on the server side. It relieves the server's workload by buffering frequently requested pages and forwards client requests to the target server on the internal network. It also returns the results obtained from the server to the client requesting a connection on the Internet. At this time, the proxy server and the target host appear to be one server to the outside world.

2. What are the main applications of reverse proxy?

Many large web sites now use reverse proxies. In addition to preventing malicious attacks on internal servers from the external network, caching to reduce server pressure and access security control, it can also perform load balancing and distribute user requests to multiple servers.

As a front-end developer, debugging the interface and sending the code to the test server every time is a very time-consuming and laborious task.

In order to improve efficiency, nginx reverse proxy was used to solve this problem.

Interface address:
test.com

Visit URL:
localhost

The core problem is that cookies cannot be written when logging in. In order to solve this problem, we took a lot of detours.

worker_processes 1;
events {
  worker_connections 1024;
}
http {
  include mime.types;
  default_type application/octet-stream;
  sendfile on;
  keepalive_timeout 10;
  server {
    listen 80;
    server_name localhost;
    
    location =/ {
      add_header X-Frame-Options SAMEORIGIN;
      root D:/workspace/;
      index index.html;
    }

    location ~* \.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css|swf|woff|woff2|ttf|json|svg|cur|vue|otf|eot)$ {
      charset utf-8;
      root D:/workspace/;
      expires 3d;
    }
    
    location = /socket/v2 {
      proxy_pass http://test.com;
      proxy_redirect off;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
      proxy_set_header Host test.com;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header REMOTE-HOST $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_connect_timeout 30;
      proxy_send_timeout 30;
      proxy_read_timeout 60;
      proxy_buffer_size 256k;
      proxy_buffers 4 256k;
    }
    
    location / {
      proxy_pass http://test.com;
      proxy_set_header Cookie $http_cookie;
      proxy_cookie_domain test.com localhost;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host test.com;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header REMOTE-HOST $remote_addr;
    }
  }
}

The core code is on three lines of code:

proxy_set_header Cookie $http_cookie;
proxy_cookie_domain test.com localhost;
proxy_set_header Host test.com;

I have only a vague understanding of the specific explanation:

  • The first one is to carry cookies,
  • The second domain that sets the cookie
  • The third one sets the real host

Important note: Do not reverse the order of the above 3, otherwise the proxy will fail, and I don’t know why.

How to debug on mobile phone?

It is impossible to access localhost directly on a mobile phone. You can connect the mobile phone and computer to the same network segment and use the computer's IP to access it.
But here only the localhost is proxied, not the computer's IP

Therefore, you need to copy the server{...} above and just change all the localhost in it to your computer IP. The final code is:

worker_processes 1;
events {
  worker_connections 1024;
}
http {
  include mime.types;
  default_type application/octet-stream;
  sendfile on;
  keepalive_timeout 10;
  server {
    listen 80;
    server_name localhost;
    
    location =/ {
      add_header X-Frame-Options SAMEORIGIN;
      root D:/workspace/;
      index index.html;
    }

    location ~* \.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css|swf|woff|woff2|ttf|json|svg|cur|vue|otf|eot)$ {
      charset utf-8;
      root D:/workspace/;
      expires 3d;
    }
    
    location = /socket/v2 {
      proxy_pass http://test.com;
      proxy_redirect off;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
      proxy_set_header Host test.com;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header REMOTE-HOST $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_connect_timeout 30;
      proxy_send_timeout 30;
      proxy_read_timeout 60;
      proxy_buffer_size 256k;
      proxy_buffers 4 256k;
    }
    
    location / {
      proxy_pass http://test.com;
      proxy_set_header Cookie $http_cookie;
      proxy_cookie_domain test.com localhost;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host test.com;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header REMOTE-HOST $remote_addr;
    }
  }
  server {
    listen 8080;
    server_name xx.xx.xx.xx;
    
    location =/ {
      add_header X-Frame-Options SAMEORIGIN;
      root D:/workspace/;
      index index.html;
    }

    location ~* \.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css|swf|woff|woff2|ttf|json|svg|cur|vue|otf|eot)$ {
      charset utf-8;
      root D:/workspace/;
      expires 3d;
    }
    
    location = /socket/v2 {
      proxy_pass http://test.com;
      proxy_redirect off;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
      proxy_set_header Host test.com;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header REMOTE-HOST $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_connect_timeout 30;
      proxy_send_timeout 30;
      proxy_read_timeout 60;
      proxy_buffer_size 256k;
      proxy_buffers 4 256k;
    }
    
    location / {
      proxy_pass http://test.com;
      proxy_set_header Cookie $http_cookie;
      proxy_cookie_domain test.com xx.xx.xx.xx;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host test.com;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header REMOTE-HOST $remote_addr;
    }
  }
}

Access method: http://xx.xx.xx.xx:8080

If the configuration is generated by the packaging tool, you can use nodejs to dynamically obtain the IP address of your computer

function getIPAdress() {   
  var interfaces = require('os').networkInterfaces();   
  for (var devName in interfaces) {      
    var iface = interfaces[devName];      
    for (var i = 0; i < iface.length; i++) {         
      var alias = iface[i];         
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {            
        return alias.address;
      }      
    }   
  } 
}

So, here is a tool for dynamically generating nginx.config

function buildNginxConfig(config) {

  function getIPAdress() {   
    var interfaces = require('os').networkInterfaces();   
    for (var devName in interfaces) {      
      var iface = interfaces[devName];      
      for (var i = 0; i < iface.length; i++) {         
        var alias = iface[i];         
        if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {            
          return alias.address;         
        }      
      }   
    } 
  }
  var cwd = process.cwd().replace(/\\/g, '/') + '/app';
  var protocol = /https|443/.test(config.ip) ? 'https' : 'http';

  var servers = [{
    browserIp: 'localhost',
    port: 80,
    root: cwd,
    serverIp: config.ip,
    protocol: protocol,
  }, {
    browserIp: getIPAdress(),
    port: 8080,
    root: cwd,
    serverIp: config.ip,
    protocol: protocol,
  }].map(function(item) {
    return `
  server {
    listen ${item.port};
    server_name ${item.browserIp};
    
    location =/ {
      add_header X-Frame-Options SAMEORIGIN;
      root ${item.root};
      index index.html;
    }

    location ~* \\.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css|swf|woff|woff2|ttf|json|svg|cur|vue|otf|eot)$ {
      charset utf-8;
      root ${item.root};
      expires 3d;
    }
    
    location = /socket/v2 {
      proxy_pass ${item.protocol}://${item.serverIp};
      proxy_redirect off;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
      proxy_set_header Host ${item.serverIp};
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header REMOTE-HOST $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_connect_timeout 30;
      proxy_send_timeout 30;
      proxy_read_timeout 60;
      proxy_buffer_size 256k;
      proxy_buffers 4 256k;
    }
    
    location / {
      proxy_pass ${item.protocol}://${item.serverIp};
      proxy_set_header Cookie $http_cookie;
      proxy_cookie_domain ${item.serverIp} ${item.browserIp};
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host ${item.serverIp};
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header REMOTE-HOST $remote_addr;
    }
  }`;
  }).join('\n');
  var str = `worker_processes 1;
events {
  worker_connections 1024;
}
http {
  include mime.types;
  default_type application/octet-stream;
  sendfile on;
  keepalive_timeout 10;
  ${servers}
}`;

  return str;
}

exports = module.exports = buildNginxConfig;

With this universal reverse proxy, you can play with any website interface as you like.

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Using nginx forward proxy to implement intranet domain name forwarding process analysis
  • Diagram of the process of implementing direction proxy through nginx
  • Difference and principle analysis of Nginx forward and reverse proxy
  • Detailed explanation of nginx forward proxy and reverse proxy
  • Interview questions about forward proxy and reverse proxy in distributed architecture

<<:  Centos7 install mysql5.6.29 shell script

>>:  js to achieve simple product screening function

Recommend

How to set the number of mysql connections (Too many connections)

During the use of mysql, it was found that the nu...

JavaScript implementation of the Game of Life

Table of contents Concept Introduction Logical ru...

Mysql join table and id auto-increment example analysis

How to write join If you use left join, is the ta...

Detailed explanation of the use of Vue Smooth DnD, a draggable component of Vue

Table of contents Introduction and Demo API: Cont...

MySQL uses events to complete scheduled tasks

Events can specify the execution of SQL code once...

Example analysis of MySQL startup and connection methods

Table of contents How to start mysqld Method 1: m...

How to view the docker run startup parameter command (recommended)

Use runlike to view the docker run startup parame...

Detailed explanation of MySQL Strict Mode knowledge points

I. Strict Mode Explanation According to the restr...

Will the deprecated Docker be replaced by Podman?

The Kubernetes team recently announced that it wi...

Discussion on the Issues of Image Button Submission and Form Repeated Submission

In many cases, in order to beautify the form, the ...

Implementation of mysql backup strategy (full backup + incremental backup)

Table of contents Design scenario Technical Point...

How to use Zen coding in Dreamweaver

After I published my last article “Zen Coding: A Q...

JavaScript flow control (branching)

Table of contents 1. Process Control 2. Sequentia...

Vue's Render function

Table of contents 1. Nodes, trees, and virtual DO...

How MySQL uses transactions

Basics A transaction is an atomic operation on a ...