What is the Nginx?

Nginx is a free and open source high-performance HTTP server and Reverse Proxy that can provide IMAP/POP3/SMATP Proxy services. Can quickly respond to static page requests and support third party function module expansion.

The advantages of Nginx

  • High concurrency and high performance (the official number of concurrent data is 50,000, but the actual number can reach 20,000-40,000)
  • Lightweight, low memory consumption
  • High stability and low downtime probability
  • Hot deployment
  • Modular design, good expansibility
  • CPU affinity

Common scenarios for Nginx

  • Static resource server
  • Dynamic matching
  • The reverse proxy
  • Gzip compression
  • Load balancing

Nginx installation configuration

MAC mirror under rapid install Homebrew tutorial: zhuanlan.zhihu.com/p/90508170

$ brew install nginx
Copy the code

Nginx common commands

  • Activation:nginx
  • View the version number:nginx -v
  • View nginx compilation parameters:nginx -V
  • Restart nginx:nginx -s reload
  • Gracefully reboot and reload the configuration file nginx.conf:/usr/local/nginx/sbin/nginx -s reload
  • Gracefully stop nginx and wait for connection requests to complete before killing worker processes/usr/local/nginx/sbin/nginx -s quit

Common commands are as follows:

Nginx -s stop Quickly shuts down nginx, possibly without saving the information, and quickly terminates the Web service. Nginx -s quit Smoothly shut down nginx, save the information, and end the Web service on schedule. Nginx-s reload is reloaded because the nginx-related configuration has been changed and needs to be reloaded. Nginx -s reopen the log file. Nginx -c filename Specifies a configuration file for nginx instead of the default. Nginx -t does not run, only tests configuration files. Nginx checks the syntax of the configuration file and tries to open the file referenced in the configuration file. Nginx -v Displays the nginx version. Nginx -v displays the nginx version, compiler version, and configuration parameters.Copy the code

Successfully see the welcome page ~! (the corresponding HTML is/usr/local/var/WWW/index HTML)

Default configuration for Nginx


Nginx. conf is the Nginx global configuration file in the Nginx installation directory. Nginx.conf. default is used as a backup of the configuration file.

Nginx USES port 8080 by default If it is found that port is occupied, can be used to kill using the process of change the port, also can modify the/usr/local/etc/nginx/nginx. Conf

http { server { listen 8181; server_name localhost; #charset koi8-r; . }}Copy the code

The configuration information in nginx.conf is as follows:

#user nobody; # worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; # set the maximum number of concurrent connections to worker_connections 1024; } HTTP {# file extension find collection include mime.types; Default_type application/octet-stream; # log format, Define alias as main #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; # call sendFile system transfer sendfile on; Tcp_nopush on; Keepalive_timeout 0; keepalive_timeout 65; # enable gizip compression #gzip on; Server {listen 8181; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; # route location / {root HTML; index index.html index.htm; IP address segment 50-100 deny 192.168.10.50/100; Allow 192.168.10.50 to allow 192.168.10.50 deny all; Deny all from top to bottom; Allow 192.168.10.50; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php${# proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # #location ~ \.php${# root HTML; # fastcgi_pass 127.0.0.1:9000; # fastcgi_index index.php; # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; # include fastcgi_params; #} # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { # deny all; #} } # another virtual host using mix of IP-, name-, and port-based configuration # #server { # listen 8000; # listen somename:8080; # server_name somename alias another.alias; # location / { # root html; # index index.html index.htm; # } #} # HTTPS server # #server { # listen 443 ssl; # server_name localhost; # ssl_certificate cert.pem; # ssl_certificate_key cert.key; # ssl_session_cache shared:SSL:1m; # ssl_session_timeout 5m; # ssl_ciphers HIGH:! aNULL:! MD5; # ssl_prefer_server_ciphers on; # location / { # root html; # index index.html index.htm; # } #} include servers/*; }Copy the code

Setting up a Static site

# port listen 8080; Server_name localhost; Location / {# root /source; HTML index.htm; }}Copy the code

Field Description:

  • Server Configures multiple virtual host parameters
  • Server_name Finds the configuration of the corresponding virtual host based on the host value in the request
  • Location Configures request routes and processes related pages
  • Root Searches the path of the resource

After the configuration is complete, run nginx -t to see if there are any errors

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
Copy the code

Then execute nginx -s reload to update the nginx configuration file, open the browser, type localhost:8080, and you should see your page.

Dynamic matching (request filtering)

Usually in the development environment or in the test environment we change the code, because the browser cache might not work, and you have to clear the cache manually to see what happens, so let’s make a configuration so that the browser doesn’t cache the relevant resources.

location ~* \.(js|css|png|jpg|gif)$ {
    add_header Cache-Control no-store;
}
Copy the code

~* .(js|css|png|jpg|gif)$Is matched to the relevant file type and then processed separately.add_headerIs to add a header to the request’s responseCache-Control no-store, tell the browser to disable the cache, and get the following results from the server each time:

Match rule

location = / {
    [ configuration A ]
}

location / {
    [ configuration B ]
}

location /documents/ {
    [ configuration C ]
}

location ^~ /images/ {
    [ configuration D ]
}

location ~* \.(gif|jpg|jpeg)$ {
    [ configuration E ]
}

Copy the code

Location = | | | ~ ~ * ^ ~ | / uri /

  • = indicates an exact match. Hit only if the requested URL path is exactly the same as the following string (highest priority).
  • ^~ indicates that if the character following the symbol is the best match, this rule is adopted and no further search is performed.
  • ~ indicates that the rule is case sensitive and is defined using re.
  • ~* indicates that the rule is defined using re and is case insensitive.
  • / universal match. Any request will be matched

Requests are filtered by status codes

Error_page 500 502 503 504/50x.html; location = /50x.html { root /source/error_page; }Copy the code

Reverse proxy resolves cross-domain


In the development of front-end and back-end separation, cross-domain problem is a very common problem. Now there are two commonly used ways to solve cross-domain problem:

  • Cross-domain Resource Request (CORS)
  • Nginx reverse proxy

Looking at the above figure, when a user requests xx.720ui.com/server1, Nginx forwards the request to a specific application on Server1, thus achieving cross-domain goals

At the same time, nginx addresses the configuration of parameters commonly used across domains.

Proxy_set_header host $http_host; Proxy_set_header x-real-ip $remote_addr; Proxy_set_header X -scheme $Scheme; Rewrite/API /(.*) /$1 break; Proxy_pass http://localhost:9000; }Copy the code
  • Intercepting paths/apis, which can be matched by re
  • Proxy_set_header allows you to redefine or add request headers that fields pass to the proxy server
  • $http_host
    r e m o t e a d d r , Remote_addr,
    Scheme is a built-in variable for Nginx
  • Rewrite: / API /user: / API /user: / API /user: / API /user (Why do I need to rewrite the URI? This is because when you use Nginx as a reverse proxy, you need to rewrite a path (or flag, as in the API example) in the original interface to make it easy to match.
  • Break Continues with the request and stops matching the location below. Note that last, similarly, stops the current request and re-initiates a request based on the rewrite matching rules, matching the rules after location from top to bottom
  • Proxy_pass proxy server

Principle: Nginx intercepts the relevant matching rules, Nginx forwards the request to http://localhost:9090, Nginx gets the request and then responds to the front end, can directly request/API /user to complete the request.

Nginx cross-domain requests a simple dome:

server { listen 80; server_name www.1212.com; location ^~ /blog/ { proxy_pass http://blog.12121.com/; }}Copy the code

All in all, we have done our best. All in all, we have done our best

Reference links:

  1. Juejin. Cn/post / 684490…
  2. Juejin. Cn/post / 684490…
  3. Juejin. Cn/post / 684490…