What is reverse proxy:

Baidu Encyclopedia Youyun:

Reverse proxy means that the proxy server accepts the connection request on the Internet, forwards the request to the server on the internal network, and returns the result obtained from the server to the client requesting the connection on the Internet. At this time, the proxy server acts as a reverse proxy server externally.

The purpose of reverse proxy varies from CDN to load balancing.

There are many mature reverse proxy software: I am familiar with nginx, which has high performance, powerful functions, and simple configuration. As a load balancing tool, it is absolutely superior.

As a programmer, the above is nonsense. Let's get down to business.

In order to complete the function quickly (actually lazy), the first thing I do is Google to see if there is a reverse management program implemented in PHP. In fact, I found it. There are 7ghost, php proxy, etc. It's a pity that they were not written with fsockopen. I don't understand it very well. If I don't understand it, it is difficult to modify and extend it to work better for my own needs, or it seems that some functions do not meet some of our tests. So I wrote a php curl based reverse proxy script.

PHP is a scripting language, which means that its execution efficiency is certainly inferior to that of C and JS. In addition, traditional PHP cannot use events to drive IO, so it cannot compare with the programs implemented by nginx and nodejs in terms of performance. If conditions permit, better implementation tools are preferred.

However, it is necessary to improve the performance under the condition that it can only be used. The secret to improving performance is to do less, and only do one thing. That is to do a good job of handling the request data and preserve the beautiful features of HTTP, such as browser caching and gzip compression. However, PHP does not do additional operations, such as load balancing and caching according to cache header contents.

The logic of implementation is mainly the following three steps:

  1. Get the content requested by the browser from $_SERVER, the legendary Request, and make some modifications.
  2. Send the request to the back-end machine with curl and wait for the legendary response of the returned content of the back-end.
  3. The response contains the header and body, which are sent to the browser for rendering using the header function and echo function respectively.
  4. Use the rewrite rule to send the request to index.php for execution. This is easy, and the code will not be pasted.

code implementation

https://pasteme.cn/68678

Reprinted from https://www.cnblogs.com/7qin/p/10651123.html