Nginx and Node. Js

“Nginx is a lightweight HTTP server with an event-driven asynchronous non-blocking processing framework that gives it excellent IO performance and is often used for reverse proxy and load balancing on the server side.”

As a front-end developer, even if you haven’t used Nginx, you must have heard this one before. This classic sentence, basically constitute everyone’s first impression of Nginx.

Nginx was released in 2004. After a few years of precipitation, it quickly became an “Internet celebrity” and became the hottest word and technology in the Internet technology circle that year. However, after years of development, to now, when the net red already “past”. Since almost all major websites are built on Nginx today, Nginx is no longer a new word, but one of the technologies of choice for Internet sites. “HTTP server”, “event-driven”, “asynchronous non-blocking”, and Nginx’s Internet popularity experience remind front-end kids of Nodejs.

In terms of work, due to the reasons of working platform and language, Nodejs is preferred to build the server for most front-end children, so as to realize some requirements, and Nginx has a natural resistance. Indeed, most of the features in Nginx can be fulfilled and implemented using node.js alone. However, in fact, Nginx and Node.js do not conflict, and both have their own areas of expertise: Nginx is better at the processing of low-level server-side resources (static resources handle forwarding, reverse proxy, load balancing, etc.), while Node.js is better at the processing of upper-layer specific business logic. The two can be combined to help front-end development.

A few words at the end of this chapter. The purpose of this article is to give a brief introduction to Nginx to show how Nginx can be a powerful tool for front-end development: you can put some of your previous Node.js work on Nginx instead of having to agonize over bags or wheels in NPM. But in fact, the seemingly simple configuration of Nginx is deeply learned. In Nginx to implement the same function, different configuration writing, the efficiency may be several times worse. This is all based on a deep understanding of Nginx principles and years of configuration and operation experience, even your back-end may not have a deep understanding of Nginx. If you really want to learn more about Nginx, you should consult professional SA or PE.

The reverse proxy

What is a reverse proxy? Internet applications are basically based on the CS basic structure, that is, client and server. A proxy is a layer of servers that provides specific services in front of the client side and the real server side, namely a proxy server.

  1. Forward agentReverse proxies are hard to understand,Forward agentYou’ve used it all the time, the wall climbing tool is actually a positive proxy tool. It will proxy the web page requests to the server outside the wall to a proxy server that can access the website. The proxy server proxy will obtain the web page content on the server outside the wall and forward it to the customer. The specific process is shown in the following figure.
    nginx-proxy

    In summary: that is, the client and the proxy server can directly access each other, belong to a LAN (LOCAL area network); The agent is to the useropaque, that is, the user needs to operate by himself or feel that his request is sent to the proxy server; The proxy server passesProxy client requestTo request a response from a server outside the domain.

  2. The reverse proxy The reverse proxyOn the contrary, look at the process diagram first.
    nginx-proxy-reverse

    The reverse proxy(In fact, this happens in almost all large web site page requests), the client sends a request to access the content on the server server. Instead, it will be sent to a proxy server, a proxy server, which will proxy requests to internal servers on the same LAN as the user, where what the user really wants is stored. Do you see the difference? The proxy server does not proxy the client, but the server, that is, it provides a unified proxy entry to the external client. The client’s requests go through the proxy server first, and the contents of the server that is really accessed on the Intranet are controlled by the proxy. In general, proxy refers to the proxy client, whereas in this case the proxy object is the server, which is what the word “reverse” means. Nginx is intended to act as this proxy. In summary: the proxy server and the real server can directly access each other, belong to a LAN (server Intranet); The agent is to the usertransparentOf, that is, no perception. With or without the reverse proxy, the user makes the same request and no additional action is required; The proxy server passesProxy internal serverReceive requests from clients outside the domain and send the requests to the corresponding internal server.

  3. There are two main reasons why Nginx reverse proxy should be used: 1) security and permissions. As you can see, with the reverse proxy, the client will not be able to access the real content server directly through requests, but must first go through Nginx. You can ensure server security by filtering out dangerous or unauthorized requests at the Nginx layer. 2) Load balancing. Such as the contents of a website is deployed in a number of servers, you can think of these machines as a cluster, then Nginx receives the client requests can be “evenly” assigned to the all servers in the cluster (internal module provides a variety of load balancing algorithm), so as to realize the load balance of the server pressure. In addition, NGINx also has the health check function (server heartbeat check), which periodically sends health check requests to all servers in the cluster through polling to check whether any servers in the cluster are in abnormal state. Once a server is found to be abnormal, Subsequent client requests from the proxy will not be sent to the server (until a later health check finds that the server is back up), thus ensuring the stability of client access.

What can the front-end do with Nginx

The following is based on a basic understanding of Nginx configuration. If not, please look up information (such as basic configuration) from the Internet to do a simple understanding. If you want to install Nginx locally, it is highly recommended that you compile the source code to make it easier to add modules later.

  1. Quick and simple access restrictions are often encountered when you want a website to be accessible to a specific group of users (such as only the Intranet of a company), or when you want a URI to be inaccessible. The Nginx configuration is as follows:

        location / {
            deny  192.168.1.100;
            allow 192.168.1.10/200;
            allow 10.110.50.16;
            deny  all;
        }
    Copy the code

    Deny and allow are in the built-in ngx_HTTP_access_module module. The matching method is from the top to the bottom, and the matching will jump out and no longer continue to match. The preceding configuration means that 192.168.1.100 is first denied access, then 192.168.1.10-200 IP address segment is allowed access (excluding 192.168.1.100), and 10.110.50.16 IP address is allowed access, and all other unmatched IP addresses are denied access. In production, it is often used in conjunction with the ngX_HTTP_geo_module module, which is built in to better manage IP address tables.

  2. Cross-domain solution In many cross-domain solutions, it is inevitable that the server side to support, using Nginx can purely front-end solution request cross-domain problem. In particular, when debugging in front and back end separation, it is often necessary to do front-end engineering locally, where the interface wants to pull actual data from the server rather than local mocks. If a local program accesses a remote interface directly, you are bound to encounter cross-domain problems. Now the mature approach is to integrate Node Proxy Server. In fact, Nginx can also be used to solve problems, even online. Start a local Nginx server. Server_name is mysite-base.com, for example, now you need to request online online interface under the www.kaola.com domain www.kaola.com/getPCBanner… When requested directly in the page, the browser will report an error:

    To circumvent the browser’s cross-domain security restrictions,Now you need to change the requested domain name to mysbase.com. A URL rule is also agreed to indicate the identity of the proxy request, and Nginx will proxy the request back to the original domain by matching the rule. The Nginx configuration is as follows:

        The proxy request URL path starts with /apis/
        location ^~/apis/ {
            # This overwrites the request by concatenating the $1 path in the first () of the regular match to the actual request and stopping subsequent matches with a break
            rewrite ^/apis/(.*)$ /The $1 break;
            proxy_pass https://www.kaola.com/;
        }  
    Copy the code

    In the page code, change the request url to http://mysite-base.com/apis/getPCBannerList.html. In this way, the data can be normally requested. In fact, nginx circumvents the browser’s cross-domain restrictions in a hack-like way and realizes cross-domain access.

  3. Suitable for PC and mobile environment now many websites have PC station and H5 station two sites, so according to the user’s browsing environment automatically switch site is very common demand. Nginx can obtain the userAgent of the requesting client through the built-in variable $http_user_agent, so as to know whether the user is on mobile or PC, and then control the redirection to H5 site or PC site. Taking the author’s local version as an example, the PC site is mysbase.com, and the H5 end is mys5.com. The Nginx configuration on the PC is as follows:

        location / {
            # Mobile and PC device adaptation
            if ($http_user_agent ~* '(Android|webOS|iPhone|iPod|BlackBerry)') {
                set $mobile_request '1';
            }
            if ($mobile_request = '1') {
                rewrite^. +http://mysite-base-H5.com; }}Copy the code

    When the browsing device is switched to mobile mode and the page is refreshed again, the site is automatically switched to H5 station. As follows:

  4. Minimizing the number of HTTP resource requests is an important part of the performance optimization of the merge request front end. Using a special request URL rule via the nginx-HTTP-concat module (example: example.com/??1.js,2.js,3.js), the front-end can combine multiple resource requests into one request, and the background Nginx will obtain each resource and combine it into a result for return. For example, the above example combines three JS resources (1.js,2.js, 3JS) into a single request, reducing browser overhead. For example, the static/js folder contains three files. The contents of the files are as follows:

    The Nginx configuration is as follows:

        # js resource http-concat
        The # nginx-http-concat module has many more parameters than the following three, please refer to the documentation for the rest
        location /static/js/ {
            concat on; Whether to enable the resource merge switch
            concat_types application/javascript; # Resource types that are allowed to merge
            concat_unique off; Whether to allow merging of different types of resources
            concat_max_files 5; # Maximum number of resources allowed to merge
        }
    Copy the code

    When the browser requests http://mysite-base.com/static/js/??a.js,b.js,c.js, it finds that the three js are returned as one, as shown in the figure below:

  5. Image processing in front end development, often need different sizes of pictures. Today’s cloud storage basically provides processing services for images (usually by adding parameters to the image links). In fact, Nginx can be dozens of lines of configuration, build a local image processing services of their own, fully able to meet the daily image cropping/scaling/rotation/image quality and other processing needs. The ngx_http_image_filter_module module is used. This module is non-basic and needs to be installed. Here is the Nginx configuration for the image zoom function:

        # Image scaling
        Url format: access to mysite-base.com/img/
        location ~* /img/(.+)$ {
            alias /Users/cc/Desktop/server/static/image/The $1; # Image server storage address
            set $width -; # Default image width
            set $height -; Image height default value
            if ($arg_width! ="") {
                set $width $arg_width;
            }
            if ($arg_height! ="") {
                set $height $arg_height;
            }
            image_filter resize $width $height; Set the image width and height
            image_filter_buffer 10M;   # Set the maximum buffer for images read by Nginx.
            image_filter_interlace on; Whether to enable image interlacing
            error_page 415 = 415.png; # Image processing error message graph, e.g. zoom parameter is not a number
        }
    Copy the code

    This is just the basic configuration. In addition, you can configure the Nginx cache using proxy_cache to avoid reprocessing images every time a request is made, reducing the processing pressure on the Nginx server. You can also pass the sumnginx-upload-moduleUse together to add the image upload function, etc.

  6. Nginx can modify the content of a page by inserting additional CSS and JS files at the bottom or top of the page. This feature requires additional module support, such as nginx_http_footer_filter or ngx_http_addition_module (both need to be installed). In your work, you often need to switch between various test environments, and sometimes you need to clean the browser DNS cache after switching through tools such as SwitchHosts. You can change the page content +Nginx reverse proxy to achieve easy and fast environment switching. Here we first write a local JS code (switchhost.js), the logic is: when the page insert hosts switch menu and click on a specific environment, the HOST IP and hostname will be stored in the cookie, and finally refresh the page; Then write a piece of CSS code (switchhost.css) to set the hosts switch-menu style. Then the Nginx script is configured:

    server { listen 80; listen 443 ssl; expires -1; # Want to broker the domain server_name m-element.kaola.com; set $root /Users/cc/Desktop/server; charset utf-8; ssl_certificate /usr/local/etc/nginx/m-element.kaola.com.crt; ssl_certificate_key /usr/local/etc/nginx/m-element.kaola.com.key; Set $switch_host '1.1.1.1' to '1.1.1.1'; Set the default value $switch_hostname. The default value is 'online' set $switch_hostname. If ($http_cookie ~* "switch_host=(.+? (? =; |$)") { set $switch_host $1; If ($http_cookie ~* "switch_hostname=(.+? (? =; |$)") { set $switch_hostname $1; } location / { expires -1; index index.html; proxy_set_header Host $host; Proxy_set_header accept-encoding ''; # reverse proxy to actual server IP proxy_pass http://$switch_host:80; Sub_filter_once off; #ngx_http_addition_module Replaces the content of the module. Insert CSS in the header, < span style =" text-align: center; text-align: center; text-align: center; text-align: center; href="/local/switchhost.css" />'; Sub_filter 'netease Kaola' 'netease Kaola :${switch_hostname}'; # nginx_http_footer_filter # nginx_http_footer_filter # Set $injected '<script language="javascript" SRC ="/local/switchhost.js"></script>'; footer '${injected}'; CSS, /local/switchhost.js, /local/switchhost.js, /local/ {root $root; }}Copy the code

    This feature opens up endless possibilities for Nginx to be used in front-end development. For example, by distinguishing local, test, and online environments, you can add a lot of development assistance to the local/test environment pages: add a resident QR code to the local page for mobile scanning and debugging; When debugging the online page locally, insert the sourceMappingURL at the bottom of the JS file for local debugging and so on.

conclusion

These are just a few simple examples to help spark interest in the front end of children’s boots. In fact, Nginx is not only limited to these small jobs, but also plays a much bigger role in actual production. Understanding and familiarity with Nginx is definitely one of the required skills for children who are interested in “big front” boots.