What is Nginx?
Nginx (engine x) is a high-performance HTTP and reverse proxy Web server. It also provides IMAP/POP3/SMTP services. Its characteristics are less memory and concurrent capability. In fact, Nginx's concurrent capability is better in the same type of Web server. Chinese mainland users use Baidu website: Baidu, Jingdong, Sina, NetEase, Tencent, Taobao, etc. There are 12.18% of the active websites in the world, about 22.2 million websites.
Nginx is a service with very simple installation, very concise configuration files (perl syntax can also be supported) and very few bugs. Nginx is very easy to start, and can almost run 7 * 24 uninterrupted. It doesn't need to be restarted even if it runs for several months. You can also upgrade the software version without interruption of service.
Nginx code is written entirely from scratch in C language. Official data tests show that it can support responses with up to 50000 concurrent connections.
Nginx action?
Http proxy, reverse proxy: as one of the most commonly used functions of Web server, especially reverse proxy.
-
Forward proxy
-
Reverse proxy
There are two load balancing strategies provided by Nginx: built-in strategy and expansion strategy. The built-in policies are polling, weighted polling and Ip hash. The expansion strategy is unrestrained. There is only what you can't think of, and there is nothing he can't do.
Dynamic and static separation. In our software development, some requests need background processing, and some requests do not need background processing (such as css, html, jpg, js, etc.). These files that do not need background processing are called static files. Let the dynamic pages in the dynamic website distinguish the constant resources from the frequently changing resources according to certain rules. After the dynamic and static resources are split, we can cache them according to the characteristics of static resources. Improve resource response speed.
Installation of Nginx
Install under Windows
- Download Nginx
http://nginx.org/en/download.html Download a stable version.
Take nginx/Windows-1.16.1 as an example, Download nginx-1.16.1.zip directly. After downloading, unzip as follows:
- Start Nginx
There are many ways to start Nginx
(1) Double click Nginx.exe directly, and a black pop-up window flashes by after double clicking
(2) Open the cmd command window, switch to the Nginx decompression directory, enter the command nginx.exe, and press enter
- Check whether Nginx starts successfully
Enter the web address directly in the browser address bar http://localhost:80 Press enter and the following page appears, indicating that the startup is successful!
- Configure listening
The configuration file of Nginx is Nginx.conf in the conf directory. The default configured port of Nginx is 80. If port 80 is occupied, it can be modified to an unoccupied port.
When we modify the configuration file Nginx.conf of Nginx, we don't need to close Nginx and restart Nginx. We just need to execute the command nginx -s reload to make the change take effect
- Turn off Nginx
If you use the cmd command window to start Nginx, closing the cmd window cannot end the Nginx process. You can use two methods to close Nginx
(1) Enter the Nginx command nginx -s stop or nginx -s quit
(2) Use taskkill / F / T / im nginx.exe
taskkill is used to terminate the process, / f is forced to terminate. / t terminates the specified process and any child processes started from it/ im represents the specified process name
Installing under Linux
1. Install gcc
To install nginx, you need to compile the source code downloaded from the official website. The compilation depends on the gcc environment. If there is no gcc environment, you need to install:
yum install gcc-c++
2. PCRE devel installation
PCRE (Perl Compatible Regular Expressions) is a Perl library, including Perl compatible regular expression libraries. The http module of nginx uses pcre to parse regular expressions, so it is necessary to install pcre library on linux. pcre devel is a secondary development library developed using pcre. Nginx also needs this library. Command:
yum install -y pcre pcre-devel
3. zlib installation
Zlib library provides many ways of compression and decompression. nginx uses zlib to gzip the contents of http package, so you need to install zlib library on Centos.
yum install -y zlib zlib-devel
4. OpenSSL installation
OpenSSL is a powerful secure socket layer cryptographic library, including the main cryptographic algorithms, common key and certificate encapsulation management functions and SSL protocol, and provides rich applications for testing or other purposes.
nginx supports not only http protocol, but also https (that is, http is transmitted over ssl Protocol), so you need to install OpenSSL Library in CentOS.
yum install -y openssl openssl-devel
5. Download installation package
Manually download the. tar.gz installation package at: https://nginx.org/en/download.html
After downloading, upload to the server / root.
6. Decompress
tar -zxvf nginx-1.18.0.tar.gz cd nginx-1.18.0
7. Disposition
Use the default configuration and execute in the nginx root directory
./configure make make install
Find the installation path: whereis nginx
Nginx common commands
cd /usr/local/nginx/sbin/ ./nginx # start-up ./nginx -c /{Specific directory}/nginx.conf # Start with a configuration file in a specific directory ./nginx -s stop # stop it ./nginx -s quit # Exit safely. nginx stops after completing the current task. ./nginx -s reload # Reload profile ps aux|grep nginx # View nginx process ./nginx -t # Check whether the configuration file is correct ./nginx -t -c /{Specific directory}/nginx.conf # Check that the configuration file for a specific directory is correct ./nginx -v # View version information
Successfully started access server ip:80
Note: if the connection fails, check whether the alicloud security group opens the port or whether the server firewall opens the port!
Related commands:
# open service firewalld start # restart service firewalld restart # close service firewalld stop # View firewall rules firewall-cmd --list-all # Query whether the port is open firewall-cmd --query-port=8080/tcp # Open port 80 firewall-cmd --permanent --add-port=80/tcp # Remove port firewall-cmd --permanent --remove-port=8080/tcp # Restart the firewall (restart the firewall after modifying the configuration) firewall-cmd --reload # Parameter interpretation # 1. Firewall CMD: a tool for operating firewall provided by Linux; # 2. -- persistent: indicates that it is set to persistent; # 3. -- add port: identifies the added port;
configuration file
main events { ... } http { server { location { ... } } }
The default configuration file of Nginx is mainly composed of five blocks: main, events, http, server and location. http, server and location belong to nested relationships.
- main: mainly controls the users and user groups to which the Nginx sub process belongs, the number of sub processes generated, the error log location and level, the pid location, the sub process priority, the cpu corresponding to the process, the number of file descriptors that the process can open, etc.
- events: controls how Nginx handles connections.
- http: the main configuration block where Nginx handles http requests.
- server: host configuration block in Nginx, which can be used to configure multiple virtual hosts.
- location: there can be multiple control blocks corresponding to the directory level in the server.
# Run user user nobody; # Number of work processes worker_processes 1; # Global error log and PID file # error_log logs/error.log; # error_log logs/error.log notice; # error_log logs/error.log info; # pid logs/nginx.pid; # Working mode and upper limit of connections events { # epoll is a way of multiplexing IO(I/O Multiplexing), # It is only used for Linux 2.6 kernel and above, which can greatly improve the performance of nginx use epoll; # Maximum number of concurrent links for a single background worker process process worker_connections 1024; } http { # Set the MIME type, which is defined by the mime.type file include mime.types; default_type application/octet-stream; # Set log output template log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log logs/access.log main; # The sendfile instruction specifies whether nginx calls the sendfile function (zero copy mode) to output the file, # For normal applications, it must be set to on, # If it is used for downloading and other application disk IO heavy load applications, it can be set to off, # To balance the disk and network I/O processing speed and reduce the uptime of the system sendfile on; # tcp_nopush on; # Connection timeout # keepalive_timeout 0; keepalive_timeout 65; tcp_nodelay on; # Turn on gzip compression gzip on; gzip_disable "MSIE [1-6]."; # Set request buffer client_header_buffer_size 128k; large_client_header_buffers 4 128k; # Set virtual host configuration server { # Listen on port 80 listen 80; # Define access using www.nginx.cn server_name www.nginx.cn; # Defines the default site root location for the server root html; # Set the access log of this virtual host access_log logs/nginx.access.log main; # Default request location / { # Defines the name of the first page index file index index.php index.html index.htm; } # Define error prompt page error_page 500 502 503 504 /50x.html; location = /50x.html { } # Static files, handled by nginx itself location ~ ^/(images|javascript|js|css|flash|media|static)/ { # After 30 days, the static file is not updated very much. You can set it larger after expiration, # If you update frequently, you can set it smaller. expires 30d; } # All PHP script requests are forwarded to FastCGI for processing. Use the default configuration of FastCGI location ~ .php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } # Access to the. htxxx file is prohibited location ~ /.ht { deny all; } } }
According to the usage of different prefixes, location can be roughly divided into ordinary location and regular location. Multiple regular locations will be matched in order. After successful matching, the locations defined later will not be matched. Multiple ordinary locations follow the "maximum matching principle", and the location with the highest matching degree will be executed. At the same time, it can also use = exact matching and ^ ~ irregular matching. It can be matched before regular matching, and the original regular matching is prohibited.
Therefore, when multiple types of location matching occur at the same time, the final execution result is that = matching takes precedence over ^ ~ matching, ^ ~ matching takes precedence over regular matching, and regular matching takes precedence over ordinary maximum prefix matching. As long as the priority location matching is successful, other locations will not be executed.