Detailed explanation of building nginx website server based on centos7 (including configuration of virtual web host)

Time:2021-4-14

1、 Nginx service foundation

Nginx (engine x) is specially developed for performance optimization. It is characterized by less memory, stability, low system resource consumption, and high processing capacity for concurrent connections (a single physical server can support 5000 concurrent requests). In fact, nginx’s concurrent capability really performs well in the same type of web server. Chinese mainland users use Baidu website: Baidu, Jingdong, Sina, NetEase, Tencent, Taobao, etc. IMAP / POP3 / SMTP service is also provided.

Advantages of nginx:

***Can be highly concurrent connection**
According to the official test, nginx can support 50000 concurrent connections. In the actual production environment, nginx can support 20000-40000 concurrent connections.
***Low memory consumption**
Nginx + PHP (fastcgi) server, under 30000 concurrent connections, starts 10 nginx processes, consumes 150MB of memory, 15MB * 10 = 150MB, opens 64 php-cgi processes, consumes 1280 memory, 20MB * 64 = 1280mb, plus the memory consumed by the system itself, consumes less than 2GB of memory.
***Low cost**
The purchase of f5big-ip, NetScaler and other hardware load balancing switches costs more than 100000 yuan to several hundred thousand yuan. Nginx is open source software, which uses 2-clause BSD like protocol, and can be used for free trial and commercial purposes.
***The configuration file is very simple**
The network is as easy to understand as the program, even the non dedicated system administrator can understand it.
***Support rewrite**
HTTP requests can be divided into different back-end server groups according to different domain names and URLs.
***Built in health check function**
If a web server at the back end of nginxproxy goes down, the access to the front end will not be affected.
***Save bandwidth**
Gzip compression is supported, and the header of browser local cache can be added.
***High stability**
For reverse proxy, the probability of downtime is very small.
** * support hot deployment**
Nginx supports hot deployment. Its automation is particularly easy, and it can run continuously for almost 7 days * 24 hours. Even if it runs for several months, it does not need to be restarted, and it can also upgrade the software version without interruption of service.

The following figure shows the performance comparison of nginx, Apache and lighttpd

So much has been said in order to highlight the powerful performance of nginx. How to build nginx website server (including the configuration of virtual web host) based on CentOS 7? Let’s continue to explain the configuration of nginx and its application in virtual machine

2、 Preparation:

1. One CentOS 7 server;

2. One CentOS 7 system disk;

3. Software packages and links needed https://www.jb51.net/softs/25646.html

4. It can also be downloaded from the official website http://www.nginx.org/ download

3、 Start to build the nginx website (mount the system disk and install the required dependency package.) :

1. All the dependent packages required for installation are provided by the system disk

2. Compiling, installing and optimizing nginx

[ [email protected]  Media] # useradd - M - S / SBIN / nologin nginx # create system users
[ [email protected]  media]# tar zxf nginx-1.12.0. tar.gz  -C / usr / SRC # unpacking
[[email protected] media]# cd /usr/src/nginx-1.12.0/
[[email protected] nginx-1.12.0]# ./configure --prefix=/usr/local/nginx 
--user=nginx --group=nginx --with-http_stub_status_module 
&& make && make install       
#Compile and install nginx
[[email protected] ~]# ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/
#Create link file of main program

In order to make the start, stop and overload of nginx service more convenient, you can edit the nginx service script. The script is compiled as follows:
[ [email protected]  ~]#VIM / etc / init.d/nginx # edit service script
#!/bin/bash
# chkconfig: - 99 20
PROG="/usr/local/nginx/sbin/nginx"
PIDF="/usr/local/nginx/logs/nginx.pid"
case "$1" in
 start)
    $PROG
 ;;
 stop)
    kill -s QUIT $(cat $PIDF)
 ;;
 restart)
    $0 stop
    $0 start
 ;;
 reload)
    kill -s HUP $(cat $PIDF)
 ;;
 *)
    echo "USAGE:$0 {start | stop | restart | reload}"
    exit 1
esac
exit 0

[ [email protected]  ~]#Chmod + X / etc / init.d/nginx # add execution permission
[ [email protected]  ~]#Chkconfig -- add nginx # add as system service
[ [email protected]  ~]#Systemctl start nginx # start nginx service to confirm the normal operation of the script
[ [email protected]  ~]# vim /usr/local/nginx/conf/ nginx.conf         #Adjusting configuration files to optimize web services
      ..............
worker_ Processes 2; # number of work processes
#error_ log logs/ error.log ; # error log file location
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid    logs/ nginx.pid The location of the PID file
events {
  Use epoll; # add this row to even {} to improve performance
  worker_ Connections 4096; each process handles 4096 connections
}

The above optimizations are implemented based on the global configuration, and the meaning of each optimization is as follows:

  • worker_ Processes: indicates the number of work processes. If the server has multiple CPUs or uses multi-core processors, the number of work processes can be specified by referring to the total number of CPU cores. The specific meaning lies in worker_ It is reflected in the connections configuration item,
  • worker_ Connections: this configuration item specifies the connections processed by each process, which are generally less than 10000 (default is 1024). It is associated with the configuration item of the number of working processes above. For example, if the number of working processes is 8 and each process processes 4096 connections, the number of connections that nginx is allowed to normally provide services has exceeded 30000 (4096 * 8 = 32768). Of course, it depends on the performance of server hardware, network bandwidth and other physical conditions.

3. Build a virtual web host based on domain name

1. HTTP configuration:

The configuration file of nginx uses the “http {}” delimitation mark to set the HTTP server, including access log, HTTP port, web directory, default character set, connection maintenance, virtual web host, PHP parsing and other website global settings, most of which are included in the sub delimitation mark “server {}”. “Server {}” represents a specific website setting.

[[email protected] ~]# vim /usr/local/nginx/conf/nginx.conf 
http {
  include    mime.types;
  default_type application/octet-stream;

  log_format main '$remote_addr - $remote_user [$time_local] "$request" '
          '$status $body_bytes_sent "$http_referer" '
           '"$http_user_agent" "$http_x_forwarded_for"';
#Remove the "#" sign at the beginning of the three lines above
  access_ log logs/ access.log  Main; # access log location

  Sendfile on; enable efficient file transfer mode
  #tcp_nopush   on;

  #keepalive_timeout 0;
  keepalive_ Timeout 65; # connection holding timeout

  #gzip on;

  server {
    Listen 80;? Web server listening port, which can be in the form of "IP address: Port"
         server_ name  www.test1.com;        #Website domain name

    Charset UTF-8; # the default character set of the website, and the "#" sign in front of it must be removed

    access_ log logs/test1. access.log  Main; # access log file name
     Location / status {# add location / status to enable status statistics. The access location is / status
      stub_ Status on; # turn on the status statistics function
      access_ Log off; # turn off logging at this location
}

    location / {
      Root / var / www / test1; # website root directory
      index  index.html  index.php Change the default home page to index.php To support PHP web pages
    }

    ;
        ..........................

    error_ Page 500 502 503 504 / 50x. HTML; # internal error feedback page
    Location = / 50x. HTML {# wrong page configuration
      root  html;
    }
    }
 }

The above configuration only builds a website service. If you want to run more than one website service, you can copy the template provided at the end of the configuration file and paste it onto the “server {}” configuration. Because there are too many “{}” in the configuration file, you need to copy it onto the original “server {}” to avoid errors, as follows:


server {
listen    80;
    server_name www.test2.com;
    charset utf-8;

    access_log logs/test2.access.log main;
     location /status {
      stub_status on;
      access_log off;
}

    location / { 
      root  /var/www/test2;
      index index.html index.php;
    }
  }

  server {
    listen    80;
    server_name www.test1.com;

        ...........................

So far, the virtual host construction has been completed, and the service needs to be restarted to verify the normal operation of the web server (DNS needs to be set by itself)

4、 Access status statistics virtual host application

[ [email protected]  ~]#Nginx - t # use this command to check the configuration file before restarting the service,
#If there is an error in the configuration file, the error line will be prompted,
#If yes, OK will be displayed. If there is an error, no error will be reported when restarting the service, but the configuration file will not take effect.
nginx: [emerg] unexpected ";" in /usr/local/nginx/conf/nginx.conf:44
#There is an error on line 44
nginx: configuration file /usr/local/nginx/conf/nginx.conf test failed
[ [email protected]  ~]#Nginx - t # the following display is OK, indicating no problem.
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

#Next, prepare the website directory and test files, establish the root directory for the two virtual web hosts, and prepare the test home page to facilitate the distinction during the test
[[email protected] named]# mkdir -p /var/www/test1
[[email protected] named]# mkdir -p /var/www/test2
[[email protected] named]# echo "www.test1.com" > /var/www/test1/index.html
[[email protected] named]# echo "www.test2.com" > /var/www/test2/index.html

Client verification:

① Visit www.test1.com Home page of

② Visit www.test1.com Status statistics page of:

The above meanings are as follows:

Active connections indicates that the current number of active connections is 2;

Server accepts handled requests represents the processed connection information, three numbers represent the number of processed connections, three successful handshakes and six processed requests.

① Visit www.test2.com Home page of

② Visit www.test2.com Status statistics page of:

Access status statistics and application of virtual host

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.

Recommended Today

Large scale distributed storage system: Principle Analysis and architecture practice.pdf

Focus on “Java back end technology stack” Reply to “interview” for full interview information Distributed storage system, which stores data in multiple independent devices. Traditional network storage system uses centralized storage server to store all data. Storage server becomes the bottleneck of system performance and the focus of reliability and security, which can not meet […]