Nginx que

Nginx is an asynchronous framework Web server that can also act as a reverse proxy, load balancer, and HTTP cache.

The characteristics of Nginx

  • Faster: Single requests are faster, and high concurrency environments have better response times.
  • High scalability: Nginx based on modular design, low coupling, has good scalability.
  • High reliability: Each worker process is relatively independent. When a worker process fails, the master process can quickly pull up a new worker sub-process to provide services. Reverse proxy.
  • Low memory consumption: in general, 10000 inactiveHTTP Keep-AliveConnections are consumed only in Nginx2.5 MBIn the memory. The maximum number of concurrent connections for Nginx damage depends on memory size.
  • Hot deployment: The separation of the master process from the worker process enables Nginx to support hot deployment. Nginx can upgrade executable files without interrupting service.

Nginx reverse proxy functionality

In the Internet era, network applications basically belong to the CS structure, that is, the client and the server. A proxy is an additional layer of servers (proxy servers) between client and server for specific functions.

Forward agent

A forward proxy is a server that is located between a client and the original server. In order to obtain the content of the original server, the client sends a request to the proxy and specifies the destination. The proxy then forwards the request to the original server and returns the obtained content to the client. A simple example of this is that the ladder we sometimes use is a forward proxy, which will proxy our requests for web pages outside the wall to a proxy server that has access to the site, and the proxy server will request the content of the web page and forward it to us.

  • A forward proxy serves clients. Clients can access resources that cannot be accessed by a forward proxy.
  • The forward proxy is transparent to the client, but not to the server, which cannot determine whether it has received a request from the client or the proxy server.

— Use an image from @conardli for a visual demonstration

The reverse proxy

Reverse proxy: a proxy server accepts requests on the network, forwards the requests to more than one server on the internal network, and returns the results on the server to the clients on the network.

  • ** Reverse proxy ** is for the server. The reverse proxy helps the server to accept and forward requests from the client, thus helping the server to complete functions such as load balancing.
  • The reverse proxy is transparent to the server, but not to us. We cannot access the server directly by request, we have to go through the proxy server first, which also protects the security of the content server to a certain extent.
  • The reverse proxy Can receive client request evenly assigned to the server in the cluster to achieve load balancing, and have Nginx server heart function examination, if a server is unusual, the proxy incoming requests will not be sent to the server, but it was not until the server is back to normal will continue to request distribution to the server, This also greatly ensures the stability of the service.

When installing Nginx, it is highly recommended to install in source-compiled mode so that modules can be added later, and since Nginx will be upgraded later, it can be installed in separate configuration and program mode. See Nginx Directory Recommendations for details

Some variables of Nginx

Nginx variables can be viewed for more comprehensive variables, but only some commonly used ones are described here.

  • Server correlation
    • $server_port Server port number
    • $server_addr Server address (IP address)
    • $server_name Server name (usually also an IP address)
    • $status Indicates the HTTP status code
  • Client-side correlation
    • $http_accept Specifies the MIME type supported by the browser
    • $http_accept Compression encoding supported by the browser
    • $http_cache_control browser cache
    • $http_user_agent User device ID
  • Links to related
    • The current URI in the $URI request is different​request_uri, which can be redirected internally.
    • $request_URI Specifies the original URI of the client request parameter
    • $request_method Specifies the request method
    • $args Request parameter, which is the parameter section after the URI

Some Nginx regular matching rules

~ case-sensitive | ~ * a case-insensitive match

! ~ don’t match case sensitive |! ~* Is case insensitive and does not match

– d with! -d is used to check whether a directory exists

The -f and! -f is used to check whether files exist

– e and! -e checks whether files or directories exist

– x and y! -x determines whether the file is executable

Basic configuration of Nginx

A basic configuration of Nginx is (check out the installed nginx.conf file).

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * {# location location path {... } location path { ... }} Server # There can be multiple servers in one HTTP {... }}Copy the code

Some common features of Nginx

To solve the cross domain

Cross-domain issues are one of the things we often encounter and are a bit of a headache, but when we use Nginx, we can take advantage of the proxy-forwarding feature to help us solve cross-domain problems.

For example, if our website is content.app.com and the server is server.app.com, we are given an interface address of/API and we access server.app.com through a proxy by starting an Nginx server to intercept front-end cross-domain requests.

server {
  # listen on port 80
	listen 80; 
	server_name content.app.com;
	location /api {
		proxy_passserver.app.com; }}Copy the code

That is, our request for content.app.com/api will be forwarded by the proxy server to server.app.com, and what we access at content.app.com is the content.app.com of the proxy server. It belongs to the same source access, so there is no cross-domain phenomenon.

Status code and incorrect configuration

server {
		Error 403 when accessing private files
		location /secret.js {
			return 403;
		}
  
  	# specify different status codes to special files
  	error_page 404 /404.html;
    error_page 500 501 502 503 /error.html;
  	The response code is 400
  	error_page 404 = 400 /400.html; 
}
Copy the code

Note: If the = sign is added after the error_page, the response is the specified response code, which is 200 by default. If the = sign is not added, the status code is the original error.

Configuring the HTTPS Service

To configure HTTPS, we need to have the http_ssl_module module enabled by Nginx at compile time, which can be viewed using the Nginx -v command

If TLS SNI support Enabled is displayed, TLS SNI support Enabled is enabled.

After that, we need to download the certificate. Generally, there will be a variety of formats after the decompression of the certificate download, using Nginx format, that is, CRT and key.

# configuration HTTPS

If you don't need HTTP->HTTPS, you can delete this configuration
server {
    listen       80;

    # configure domain name
    server_name www.safe.com safe.com;

    # Add STS and allow all subdomains to support it
    add_header strict-transport-security 'max-age=31536000; includeSubDomains; preload';

    Configure these HTTP accesses to redirect all 301 to HTTPS,
    rewrite^ (. *) https://www.safe.comThe $1 permanent;
    Rewrite (' break '); rewrite (' break '); rewrite (' break ');
    Rewrite: / / rewrite: / / rewrite: / / rewrite: / /
    And 302 # rewrite for redirect after temporary redirect, url address bar shows that, after the redirection crawlers don't update url
    Rewrite: / / rerewrite: / / rerewrite: / / rerewrite: / /
}

# configuration HTTPS
server {
    # configure domain name
    server_name www.safe.com safe.com;

    HTTPS default port
    listen 443;

    # Add STS and allow all subdomains to support it
    add_header strict-transport-security 'max-age=31536000; includeSubDomains; preload';

    # HTTPS configuration
    ssl on;
    ssl_certificate /ssl/ssl.crt;
    ssl_certificate_key /ssl/ssl.key;

    Others can be processed according to normal configuration.
}
Copy the code

Suitable for PC and mobile environments

Although the adaptive function of many cross-end applications is becoming more and more perfect, there are still many websites that have both PC and H5 sites, so switching sites according to users’ devices is also a common requirement. We need to use the built-in http_user_agent variable to retrieve the user’s device information and return different nodes based on the device.

location / {
	# Mobile device matching
  if ($http_user_agent ~* '(Android|webOS|iPhone|iPad|BlackBerry)') {
    set $mobile_request '1';
  }
  if ($mobile_request = '1') {
    rewrite^. + https://mobile.com 
  }
}
Copy the code

The image processing

In front-end development, we sometimes need different sizes of images, and some cloud services provide services with links to add parameters to get different sizes of images. We can do this by using a non-base module (installed) ngx_HTTP_image_filter_module.

    # Image zoom processing
    The url format for image processing is 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 -; # Default image height
        if ($arg_width! ="") {
            set $width $arg_width;
        }
        if ($arg_height! ="") {
            set $height $arg_height;
        }
        image_filter resize $width $height; # Set image width and height
        image_filter_buffer 10M;   # set the maximum buffer that Nginx can read from images.
        image_filter_interlace on; Whether to enable interlaced image scanning
        error_page 415 = 415.png; Error: The zoom parameter is not a number
    }

Copy the code

Anti-theft chain processing

The Nuggets have also turned on anti-leach in the past due to the rampant use of images, and anti-leach is one of the ways we need to turn it on to protect our servers.

server {
  # Match all images
  location ~* \.(gif|jpg|png|bmp)$ {
    Regex = 0; regex = 1; regex = 0
    valid_referers none blocked server_names www.reaper.com;
    Error 403 is returned if the validation fails
    if ($invalid_referer) {
      return 403; }}}Copy the code

conclusion

The learning of Nginx was completed while I was configuring my personal blog website Reaper Lee, hoping to help some students who are preparing to learn or just getting started with Nginx. However, for the front end of the gradual full stack, learning the configuration of the server seems to have become a required skill. You can also follow my GitHub to learn and make progress together!

Reference links:

  • Essential Nginx knowledge for front-end developers – ConardLi
  • Nginx tutorial