Understanding of nginx load balancing
nginx is a lightweight, high-performance webserver. It can mainly do the following two things:
- As an http server (same effect as apache)
- Act as a reverse proxy server to achieve load balancing
Now nginx can be seen everywhere, and you often see the words nginx displayed on webpages after downtime. This also shows that nginx is accepted by more and more users due to its high performance, simple use and configuration, and open source. used.
The first one acts as an http server and combines with the php-fpm process to process incoming requests. nginx itself does not parse PHP. It just acts as a server to accept requests from the client. If it is a PHP request, Then it is handed over to the php process for processing, and the result after the php processing is completed is sent to the client. This is very simple. After installing nginx+php-fpm, configure the respective configuration files and start it. The operating principle can be seen in the following explanation:
Nginx does not support direct calling or parsing of external programs. All external programs (including PHP) must be called through the FastCGI interface. The FastCGI interface is a socket under Linux (this socket can be a file socket or an ip socket). In order to call a CGI program, a FastCGI wrapper is also needed (a wrapper can be understood as a program used to start another program). This wrapper is bound to a fixed socket, such as a port or file socket. When Nginx sends a CGI request to this socket, the wrapper receives the request through the FastCGI interface, and then spawns a new thread. This thread calls the interpreter or external program to process the script and read the return data; then, the wrapper The returned data is passed to Nginx along the fixed socket through the FastCGI interface; finally, Nginx sends the returned data to the client. This is the entire operation process of Nginx+FastCGI, as shown in the figure below.
The above paragraph explains the operating mechanism of nginx+fastcgi. The request will be matched in the nginx configuration file and processed accordingly, such as returning the error file directly (there is a little difference between this and the above, I guess nginx can perform analysis similar to the above picture on static files such as HTML), and use the PHP process to process PHP requests (there can be multiple PHP processes here).
The second is to use reverse proxy load balancing. This is actually very simple. To put it simply, you define a group of servers, match the requests, and transfer the requests to any one of the servers for processing to reduce the load on each server. To reduce the pressure, first take a look at the definition of reverse proxy online:
The Reverse Proxy method refers to using a proxy server to accept connection requests on the Internet, then forward the request to the server on the internal network, and return the results obtained from the server to the client requesting a connection on the Internet , at this time the proxy server appears as a reverse proxy server to the outside world.
Reverse proxy is the opposite of forward proxy (or proxy). You must have heard of proxy. In order to access resource B more conveniently, resource B is indirectly accessed through resource A. The characteristic is that the user knows what he will eventually access. What is the website, but reverse proxy users do not know what processing is done behind the proxy server. The real processing server of the service in the reverse proxy is placed on the intranet, and the external network can only access the reverse proxy server, which greatly Improved security.
Install software
nginx installation is very simple
1. The environment required to install nginx, pcre (for rewrite), zlib (for compression), ssl, you can also download, compile and install this yourself
yum -y install zlib;
yum –y install pcre;
yum –y install openssl;
2. Download and install nginx-*.tar.gz.
tar –zxvf nginx-1.2.8.tar.gz –C ./;
cd nginx-1.2.8;
./congigure --prefix=/usr/local/nginx;
make && make install;
3. Configuration
When configuring here, you only need to modify the content between http{}. The first place to modify is to set up the server group and add
between http nodes.upstream myServer{
#HereUpstream in nginx supports the following methods: polling (by default, all servers are accessed one by one in chronological order. If a server is down, it will be automatically eliminated), weight (the location probability of the server is proportional to the weight, this It can be configured when the server configuration is uneven), ip_hash (hash calculation is performed on each requested IP, and the corresponding server is allocated according to certain rules), fair (requests are allocated according to the response time (rt) of each server) , rt knows priority allocation), url_hash (distributes requests according to the hash value of the accessed URL), I use the default rotation method here.
Point the request to myServer
location / {
proxy_pass http://myServer;
}The complete document (with comments removed) is as follows:
worker_processes <span>1</span><span>; events { worker_connections </span><span>1024</span><span>; } http { include mime.types; default_type application</span>/octet-<span>stream; sendfile on; keepalive_timeout </span><span>65</span><span>; upstream myServer{ server www.myapp1.com:</span><span>80</span><span>; server www.myapp2.com:</span><span>8080</span><span>; } server { listen </span><span>80</span><span>; server_name my22; location </span>/<span> { proxy_pass http:</span><span>//</span><span>myServer;</span> <span> } } }</span>
Set up reverse proxy backend as load balancing between two servers
You can see that there are two server addresses in the previous step, www.myapp1.com:80 and www.myapp2.com:8080. I installed the above nginx on the virtual machine. I installed these two servers on this server. In the win8 system of the computer, using apache's virtualhost, two domain names are set up. The codes under the two domain names are independent of each other, and the settings are also very simple:
1. Set up apache configuration file
I am using the xampp integrated environment. There are two places to modify. Add the listening port in httpd.conf
Listen 8080
That is to say, this place monitors two ports
Listen 80
Listen 8080Check whether the following sentence is open. If not, open it. Open it as shown below
<span># Virtual hosts Include conf</span>/extra/httpd-vhosts.confAdd the following content in httpd-vhosts.conf,
<virtualhost>80><span> ServerName www.myapp1.com #对应的域名,负载均衡的服务器地址 DocumentRoot E:\soft\xampp\htdocs\www.myapp1.com #代码文件夹 </span></virtualhost> <virtualhost>8080><span> ServerName www.myapp2.com DocumentRoot E:\soft\xampp\htdocs\www.myapp2.com </span></virtualhost>Modify the windows hosts file and add the following content
<span>127.0</span>.<span>0.1</span><span> www.myapp1.com </span><span>127.0</span>.<span>0.1</span> www.myapp2.comModify the /etc/hosts file of Linux and add the following content
<span>192.168</span>.<span>1.12</span><span> www.myapp1.com #这里前面的地址对应我win8本机的ip地址 </span><span>192.168</span>.<span>1.12</span> www.myapp2.com
I put a file index.php in www.myapp1.com:80 [E:softxampphtdocswww.myapp1.comindex.php]
A file index.php is also placed in www.myapp2.com:8080 [E:softxampphtdocswww.myapp2.comindex.php]
The content in the file is basically the same, except that I'm the myapp2 is different. One is myapp1 and the other is myapp2.
If you can enter www.myapp1.com:80 and www.myapp2.com:8080 in the win8 browser to see different effects
And when you see the following result under centos (beautified by yourself), it means that the configuration is successful
[root@bogon nginx]# curl www.myapp1.com:<span>80</span><span> I</span><span>'</span><span>m the myapp1<br>【view】1</span> [root@bogon nginx]# curl www.myapp2.com:<span>8080</span><span> I</span><span>'</span><span>m the myapp2<br>【view】1</span>
<span>php </span><span>session_save_path</span>("./"<span>); </span><span>session_start</span><span>(); </span><span>header</span>("Content-type:text/html;charset=utf-8"<span>); </span><span>if</span>(<span>isset</span>(<span>$_SESSION</span>['view'<span>])){ </span><span>$_SESSION</span>['view'] = <span>$_SESSION</span>['view'] + 1<span>; }</span><span>else</span><span>{ </span><span>$_SESSION</span>['view'] = 1<span>; } </span><span>echo</span> "I'm the myapp2<br>"<span>; </span><span>echo</span> "【view】{<span>$_SESSION</span>['view']}";
See the effect
After everything is ok, you can access it through the browser to see the effect
Forgot to mention, the address of nginx proxy server is http://192.168.1.113,
After entering http://192.168.1.113/index.php in the browser, keep refreshing, you will find that it will be in
I'm the myapp2、I'm the myapp1
When these two pages are exchanged back and forth, the view will be increased once without refreshing twice. This also proves the default rotation training method mentioned earlier, but there is another common problem here. When the user visits the website , without processing, the session will be saved on different servers (I use two different folders to simulate two servers here), and there may be multiple sets of session data. How to solve this problem? The next article will talk about it This question is actually very simple.
The copyright of this article belongs to the author iforever (luluyrt@163.com). Any form of reprinting is prohibited without the author's consent. After reprinting the article, the author and the original text link must be provided in an obvious position on the article page, otherwise the right to pursue legal liability is reserved. .
The above has introduced centos+nginx to configure load balancing from scratch, including all aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

The session ID should be regenerated regularly at login, before sensitive operations, and every 30 minutes. 1. Regenerate the session ID when logging in to prevent session fixed attacks. 2. Regenerate before sensitive operations to improve safety. 3. Regular regeneration reduces long-term utilization risks, but the user experience needs to be weighed.

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1
Easy-to-use and free code editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.