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

Introduction to vim plugin installation under Linux system

Table of contents Install vim plugin manager Add ...

Detailed explanation of the use of mysql explain (analysis index)

EXPLAIN shows how MySQL uses indexes to process s...

Optimization analysis of Limit query in MySQL optimization techniques

Preface In actual business, paging is a common bu...

Example of pre-rendering method for Vue single page application

Table of contents Preface vue-cli 2.0 version vue...

HTML structured implementation method

DIV+css structure Are you learning CSS layout? Sti...

JavaScript pie chart example

Drawing EffectsImplementation Code JavaScript var...

Two practical ways to enable proxy in React

Two ways to enable proxy React does not have enca...

React implements the expansion and collapse function of complex search forms

Give time time and let the past go. In the previo...

Summary of common commands in Dockerfile

Syntax composition: 1 Annotation information 2 Co...

Implementation of CSS Fantastic Border Animation Effect

Today I was browsing the blog site - shoptalkshow...

What are your principles for designing indexes? How to avoid index failure?

Table of contents Primary key index Create indexe...

Ten important questions for learning the basics of Javascript

Table of contents 1. What is Javascript? 2. What ...

How to configure jdk environment under Linux

1. Go to the official website to download the jdk...