Sort out what you need to know about Nginx at the front end.

What is Nginx

Definition: Nginx (Engine X) is a high-performance HTTP and reverse proxy Web server.

By definition, Nginx belongs to the same HTTP server as the services we build using NodeJS.

  • reverseSends a request to the internal server on behalf of an external network user and returns the response to the external user. (Outside to inside)
  • thenForward agentThat is: on behalf of internal network users to the external server to send a connection request, get the response back to internal users. (Inside out)
  • The reverse proxy server is located between the user and the target server. The reverse proxy server is usually used for Web acceleration. That is, the reverse proxy is used as the front of the Web server to reduce the load on the network and the server and improve the access efficiency.

Second, get started quickly

1. Install

Nginx can be installed on most major operating systems, including Windows, MAC, and Linux.

Nginx installation and configuration – rookie tutorial

Installation caution Remember the installation location.

Common commands

nginx -s reopen 	# restart Nginx
nginx -s reload 	Reload the Nginx configuration file, and then gracefully restart Nginx
nginx -s stop   	# Force to stop Nginx service
nginx -s quit   	Stop the Nginx service gracefully (after all requests are processed)
nginx -h 		# Open help messages
nginx -v 		Display version information and exit
nginx -V		Display version and configuration option information, then exit
nginx -t		Check the configuration file for syntax errors and exit
nginx -T	 	Check the configuration file for syntax errors, dump and exit
nginx -q 	  	Mask non-error messages during configuration file detection
nginx -p prefix   	# configure the prefix path (default :/usr/share/nginx/)
nginx -c filename	/etc/nginx/nginx.conf
nginx -g directives 	Set global directives outside the configuration file
killall nginx		# Kill all nginx processes

Copy the code

3. Common configuration items

  • Start with basic configuration
# define users and user groups to run Nginx
user  nginx;
# Number of nginx processes. It is recommended that the value be set to the total number of CPU cores
worker_processes  1;   
Error log store directory and type
error_log  /var/log/nginx/error.log warn;
# process file
pid        /var/run/nginx.pid;

events {
    worker_connections  1024; # Maximum number of connections per process (maximum number of connections = number of connections * number of processes)
}

Configure the HTTP server
http {
    include       /etc/nginx/mime.types;   File extension and type mapping table
    default_type  application/octet-stream;  The default file type
    Set the log format
    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  /var/log/nginx/access.log  main;   # nginx access log location
    Sendfile specifies whether nginx calls sendFile to output files. For common applications, set it to on.
    If it is used for heavy disk I/O applications such as downloads, you can set it to off to balance disk and network I/O processing speed and reduce system load.
    # Note: Change this to off if the image does not display properly.
    sendfile        on;   
    tcp_nopush     on;    Prevent network congestion
    keepalive_timeout  65;  # Long connection timeout, in seconds
    gzip  on;  Enable gzip compression
    include /etc/nginx/conf.d/*.conf; Conf files in the conf. D folder will be included in the nginx configuration
    # Service configuration
    server{
        listen 80;# monitor port
        # root directory
        location / {
            proxy_pass http://myproject; Select which server list}}}Copy the code

1. Configure the structure

The module function
main The global configuration of nginx takes effect globally.
events The configuration affects the Nginx server or network connections to users.
http You can nest multiple servers, configure proxy, cache, log definition and most functions and configure third-party modules.
server Configure virtual host parameters. One HTTP server can have multiple servers.
location Configure the routing of requests and the processing of various pages.
upstream Configuring back-end server addresses is an integral part of load balancing configuration.

2. Built-in variables

Variable name function function
$host Host in the request information, if there is no Host line in the request, is equal to the server name set
$request_method Client request type, such as GET or POST
$remote_addr Client IP address $ARgs Parameter in the request
$content_length Content-length field in the request header
$http_user_agent Client Agent information
$http_cookie Client cookie information
$remote_port Client port
$server_protocol The protocol used in the request, e.g. HTTP/1.0, ·HTTP/1.1
$server_addr Server address
$server_name Server name
$server_port Port number of the server

3. Perform other operations

1. Declare variables & assign variables

Declare a variable and assign a value to it
set $username "alan";
Copy the code

2. Read the cookie

Read the cookie carried by the request, where keyName is the key of the cookie
$cookie_keyName;
Copy the code

3. If statement

set $env $cookie_ENV;
# if ==! =
if ($cookie_ENV == "dev") {
    rewrite ^/website/blog/index.dev.html;
}
Copy the code

4. File | directory judgment

statements function
-f File exists
-d Directory exists
! -d Directory does not exist
-e The file or directory exists
! -e The file or directory does not exist
-x File executable
! -x File not executable
# Return HTML if the file or directory does not exist
if(! -e $request_filename) {rewrite ^/website/blog/index.html;
}
Copy the code

5. Set the response header and status code

Set the response header add_header in the server
add_header Access-Control-Allow-Origin *;

location / {
    Proxy_set_header is usually used in the proxy case:
    proxy_set_header Host 127.0.0.1;
    Set the culled header field
    proxy_hide_header Expires; 
    Set the status code to return
    return 200;
}
Copy the code

Nginx common operation commands

1. View the nginx installation directory

ps -ef | grep nginx

# root 4593 1 0 Jan23 ? 00:00:00 nginx: master process /usr/sbin/nginx
Copy the code

2. View the directory of the nginx.conf configuration file

View the configuration file directory by checking that the configuration is correct

nginx -t

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

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok

3. Check whether the nginx configuration syntax is correct

nginx -t

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

The -c parameter specifies the path to the configuration file. If the -c parameter is not used, Nginx loads the nginx.conf file in the conf subdirectory of its installation directory by default.

4. Start or restart the nginx service

If nginx is already enabled, an error will be reported when nginx -c is executed again
/usr/sbin/nginx -c /etc/nginx/nginx.conf

Restart the nginx service
/usr/sbin/nginx -s reload
Copy the code

5. Stop the nginx service

# Fast force stop Nginx service
/usr/local/nginx/sbin/nginx -s stop

# Gracefully stop nginx service
/usr/local/nginx/sbin/nginx -s quit
Copy the code

The quit parameter first closes the listening port, stops receiving new connections, processes all connections currently being processed, and finally exits the process.

6. View nginx logs

Nginx logs are classified into access logs and error logs

cat /etc/nginx/nginx.conf Print the contents of the entire file directly
tail -f /etc/nginx/nginx.conf # Output logs in real time
Copy the code

5. Nginx application in the front end

1. Static resource server

Usually, nginx will be deployed on our CDN source server to host static resources. When accessing a specific path under the domain name (such as /static), it will be forwarded to the local directory file on the server. When accessing the directory with index.html, it will be directly opened as a page.

If the page has just been configured to display is a default HTML:

  • configuration
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    access_log  /usr/local/etc/nginx/logs/access.log;  #nginx request log address
    sendfile        on;
    keepalive_timeout  65;
    Static file service
    server {
        location / {
            root /data/www; # the root directory
            autoindex on; Automatically display the index.html page in the directory
            expires 30d; Cache for 30 days}}}Copy the code

2. The front and back ends are separated

In the separated mode of the front and back ends, the front and back ends deploy their own projects respectively, and the request sent from the front end to a service port of the back end will cause cross-domain. Therefore, Nginx is used to set forwarding to solve the cross-domain problem.

Nginx is used as a static resource server to host static files such as HTML, CSS, AND JS images, and then proxies Ajax requests that meet certain criteria to back-end services. Can realize the deployment of the front and back end projects.

See my other article for more details: How to split projects on the server deployment front and back

3. Load balancing

Load balancing: Simply understood, requests are distributed to multiple servers. The allocation policy takes into account the maximum load of the service, the current load, and other information.

Here are some suggestions: Front-end Nginx knowledge comb – load balancing

4. Deploy multiple front-end test environments

During packaging, the front end packages different HTML files for multiple environments, and then returns the HTML of the corresponding environment according to the cookie judgment environment.

This allows code to be completely isolated, so that only code from that environment appears.

location^ ~ /blog {
    set $env "dev1";
    if($cookie_ENV ! ="") {
        set $env $cookie_ENV;
    }
    The # HTML file is not set to strong cache, each time the server to confirm whether to update
    if ($request_filename ~ .*\.(htm|html)$) {
        add_header Cache-Control no-cache;
    }
    if(! -e $request_filename) {rewrite^ (. *) /website/$env/blog/index.$env.html last; }}Copy the code

5. Multiple domain names point to services or static files on the same server

Since nginx configuration and logging for multiple projects are best maintained and deployed separately, take advantage of nGINx modularity and divide them into multiple sub-configuration files.

  • nginx.conf: Import file
http {
    Load additional child Nginx configurations
    include /etc/nginx/conf.d/*.conf;
}
Copy the code
  • The server renders the service configuration file/etc/nginx/conf.d/alanyf.ssr.com.conf
# nodejs service
server {
    listen 80;
    server_name alanyf.ssr.com; # the domain name
    access_log /data/web_deployment/log/nginx/alanyf.ssr.com.access.log;
    error_log /data/web_deployment/log/nginx/alanyf.ssr.com.error.log;
    
    location /ssr {
        root /data/sites/ssr/;
        proxy_pass http://127.0.0.1:3000; Proxy to server local port 3000
        proxy_set_header Host alanyf.ssr.com;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header referer "http://$host"; break; }}Copy the code
  • Blog site static resource profile/etc/nginx/conf.d/alanyf.blog.com.conf

# static file
server {
    listen 80;
    server_name alanyf.blog.com; # the domain name
    access_log /data/web_deployment/log/nginx/alanyf.blog.com.access.log;
    error_log /data/web_deployment/log/nginx/alanyf.blog.com.error.log;
    
    location /blog {
        root /data/sites/blog;
        The # HTML file is not set to strong cache, each time the server to confirm whether to update
        if ($request_filename ~ .*\.(htm|html)$) {
            add_header Cache-Control no-cache;
        }
        if(! -e $request_filename) {rewrite^ / (. *)/blog/index.html; }}}Copy the code
  • Document site static resource profile/etc/nginx/conf.d/alanyf.docs.com.conf
# static file
server {
    listen 80;
    server_name alanyf.docs.com; # the domain name
    access_log /data/web_deployment/log/nginx/alanyf.docs.com.access.log;
    error_log /data/web_deployment/log/nginx/alanyf.docs.com.error.log;
    
    location /docs {
        root /data/sites/docs;
        The # HTML file is not set to strong cache, each time the server to confirm whether to update
        if ($request_filename ~ .*\.(htm|html)$) {
            add_header Cache-Control no-cache;
        }
        if(! -e $request_filename) {rewrite^ / (. *)/docs/index.html; }}}Copy the code

6. Configure HTTPS on nginx

For details, see configuring HTTPS for nginx

Six, reference

  • Front-end Nginx knowledge comb – black maple – Nuggets
  • Nginx essentials for front-end developers – ConardLi – Nuggets
  • Nginx super detailed common operation commands
  • How do you deploy the front and back end separation project on the server
  • Nginx configuration HTTPS