Deep learning content about Nginx

Source: Internet
Author: User
Tags geoip openssl md5 openssl rsa openssl version openssl x509 ssl connection asymmetric encryption maxmind
This article mainly introduces about Nginx deep learning content, has a certain reference value, now share to everyone, the need for friends can refer to

First, static and dynamic separation

separating dynamic requests from static requests through the middleware.
Cause: isolate resources, reduce unnecessary request consumption, and reduce request latency.

Dynamic and static request Legends:

    • Basic Configuration

Upstream php_api{    server 127.0.0.1:8080;} server {    root filePath;    Location ~ \.php$ {        Proxy_pass http://php_api;        Index index.html index.htm;    }    Location ~ \. (jpg|png|gif) {        expires 1h;        gzip on;    }}

Ii. Rules of Rewrite

1. Scene:

    • URL access jump, support development design (page jump, compatibility support, display effect, etc.)

    • SEO optimization

    • Maintenance (background maintenance, traffic forwarding, etc.)

    • Safety

2. Configuration syntax

Rewrite

    • Configuration syntax: rewrite regex replacement [flag];

    • Default: None

    • Context:server,location,if

Example: rewrite ^(.*)$ /pages/main.html break;

    1. Regex (Regular)

the pcregrep command in Linux can be used to test regular expressions.
| Meta-character | meaning |
. Match any character other than line break
? Repeat 0 or 1 times
+ Repeat 1 or more times
D Match numbers
* Greedy mode, how many matches are there?
^ Match start
$ Match end
N Repeat n times
{N,} Repeat N or more times
C Match a single character C
[A-z] Match any one of a-Z lowercase letters
\ Transfer character
( ) Used to match () the content between, through $1 , $2 call
    1. Flag

Flag meaning
Last Stop rewrite detection
Break Stop rewrite detection
redirect Returns 302 temporary redirect, the address bar displays the address after the jump
Permanent Return 301 Permanent Redirect, the address bar will show the address after the jump
    • 301 permanent redirection: Unless the user cleans up the cache, the next request will still request a redirect

    • 302 Temporary Redirect: The next time the user requests will also go through service end multiplicity orientation

    • The difference between last and break: A new connection is created, and the match continues down. Break will stay directly at that level.

    • Redirect: After you close nginx, the redirection will fail.

    • Permanent: If you close Nginx, you will also be redirected to the new address.

Example:
Location/{    # file does not exist, direct access to 4399    if (!-f $request _filename) {        rewrite ^/(. *) $ http://www.4399.com;    }}
    1. Priority level

      1. Execute the rewrite directive for the server block

      2. Perform a location match

      3. Execute the rewrite in the selected location

Third, Nginx's advanced module

1. Secure_link_module Module

(1) Develop and allow checking the authenticity of requested links and protecting resources from unauthorized access
(2) Limit link effective period

Legend:

    • Configuration syntax

      • Configuration syntax: SECURE_LINK_MD5 expression;

      • Default: None

      • Context:http,server,location

      • Configuration syntax: Secure_link expression;

      • Default: None

      • Context:http,server,location

      • Secure_link

      • Secure_link_md5

Simple Configuration Example:

Root/opt/app/code;location/{    secure_link $arg _md5, $arg _expires;    Secure_link_md5 "$secure _link_expires$uri custom string";    if ($secure _link = "") {        return 403;    }    if ($secure _link = "0") {        return 410;    }}

Script that generates the URL:

#!/bin/bashservername= "your servername" download_file= "/download/test.img" time_num=$ (date-d "2018-10-18 00:00:00" +%s ) secure_num= "Custom string" res=$ (echo-n "${time_num}${download_file} ${secure_num}" |openssl md5-binary | OpenSSL base64 | TR + / -_ | tr-d =) echo "Http://${servername}${download_file}?md5=${res}&expires=${time_num}"
Note:1. Custom strings in the build script and custom strings in the configuration should be consistent. 2. The validation rules remain consistent. 3, if there is no OpenSSL, can be installed yum.

2. Geoip_module Module

based on IP address matching maxmine GeoIP binary file, read IP region information.
The default installation of Nginx is not installed GeoIP This module, the installation command:
yum install nginx-module-geoip
    • Usage scenario:

      • Make HTTP access rules at home and abroad

      • Make HTTP access rules for different domestic cities

    • Use steps:

      • wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz

      • wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz

      • load_module "modules/ngx_http_geoip_module.so";

      • load_module "modules/ngx_stream_geoip_module.so";

      1. Install GeoIP: yum install Nginx-module-geoip , install complete view/etc/nginx /module directory, if there is a corresponding so file, then the installation succeeds

      2. At the beginning of the/etc/nginx/nginx.conf configuration file, add

      3. To download the GEO partition file:

      4. li>

        Use gunzip command to extract downloaded files

Configuration examples

geoip_country/etc/nginx/geoip/geoip.dat;geoip_city/etc/nginx/geoip/geolitecity.dat;server{    Location/myip {        Default_type Text/plain;        Return "$remote _addr $geoip _country_name $geoip _country_code $geoip _city";    }

Four, Nginx-based HTTPS services

1. Why HTTPS is required

    • Cause: HTTP is not secure

      1. Transfer of data by middleman, information disclosure

      2. Data content hijacking, tampering

2, the implementation of HTTPS protocol

encrypt and authenticate the transmitted content
    • Symmetric and Asymmetric encryption

    • The principle of HTTPS encryption protocol

    • Steps for clients to communicate with a Web server using HTTPS

      1. Client accesses Web server using HTTPS URL, requires SSL connection with Web server

      2. When a Web server receives a client request, it sends a copy of the Web site's certificate information (the certificate contains the public key) to the client

      3. The client's browser and Web server begin to negotiate the security level of the SSL connection, which is the level of information encryption

      4. The client's browser establishes a session key based on both agreed security levels and then encrypts the session key using the Web site's public key and transmits it to the Web site

      5. The Web server decrypts the session key with its own private key

      6. The Web server uses session keys to encrypt communication with the client

Communication schematic diagram:

3. Certificate Signature Generation

Preparation steps:

    1. Confirm that OpenSSL has no installation,openssl version

    2. Nginx has no compile http-ssl-module,nginx -V

To generate a self-visa book Step:

    1. Generate Key key

      • openssl genrsa -idea -out ronaldo.key 1024

    2. Generate a Certificate signing request file (CSR file)

      • openssl req -new -key ronaldo.key -out ronaldo.csr

      • When prompted to enter a challenge password, indicates that the CA file needs to change the other password, enter directly.

package The files generated by the above two steps send to the signing authority to complete the certificate signing
    1. Generate a certificate signature file (ca file)

      • OpenSSL x509-req-days 3650-in ronaldo.csr-signkey ronaldo.key-out ronaldo.crt

Configuration syntax:

    • Ssl

      • Configuration syntax: SSL on | Off

      • Default: SSL off;

      • Context:http,server

    • Ssl_certificate (where the CRT files are located)

      • Configuration syntax: Ssl_certificate file;

      • Default: None

      • Context:http,server

    • Ssl_certificate_key (key file location)

      • Configuration syntax: Ssl_certificate_key file;

      • Default: None

      • Context:http,server

Simple example:

server {    listen 443;    server_name locahost;    SSL on;    SSL_CERTIFICATE/ETC/NGINX/SSL_KEY/RONALDO.CRT;    Ssl_certificate_key/etc/nginx/ssl_key/ronaldo.key;    Index index.html index.htm;    Location/{        root/opt/app/code;    }}

After the configuration is complete:

    1. To stop Nginx: nginx -s stop -c /etc/nginx/nginx.conf , you will be asked to enter the Ronaldo.key password.

    2. Start Nginx: nginx -c /etc/nginx/nginx.conf You will also be asked to enter a password.

    3. To see if port 443 is enabled:netstat -luntp | grep 443

4. Configure the certificate required by Apple

    1. Server-all connections using TLS1.2 or more (OpenSSL 1.0.2)

      • Version:openssl version

      • Self-visa book encryption signature algorithm type and number of public key bits:openssl x509 -noout -text -in ./ronaldo.crt

      • Upgrade the OpenSSL script

#!/bin/bashcd/opt/downloadwget Https://www.openssl.org/source/openssl-1.0.2k.tar.gztar ZXF OPENSSL-1.0.2K.TAR.GZCD openssl-1.0.2k./config--prefix=/usr/local/opensslmake && make installmv/usr/bin/ Openssl/usr/bin/openssl. Offmv/usr/include/openssl/usr/include/openssl. Offln-s/usr/local/openssl/bin/openssl/usr/bin/opensslln-s/usr/local/openssl/include/openssl/usr/include/ Opensslecho "/usr/local/openssl/lib" >>/etc/ld.so.confldconfig-vopenssl version-a
    1. The HTTPS certificate must be signed with the hash algorithm above SHA256

    2. HTTPS certificates must use RSA 2048-bit or ECC 256-bit public key algorithm

    3. Using forward encryption technology

generate CRT files directly from the key file by self-sign, in line with Apple's requirements:
    • openssl req -days 36500 -x509 -sha256 -nodes -newkey rsa:2048 -keyout ronaldo.key -out ronaldo_apple.crt

    • -keyoutThe parameter will be regenerated into a key file (no protection Code), reload Nginx will not have to enter the password again.

    • After you generate the CRT files, you only need to modify the configuration file to

    • Directly generate a key without a protection code:openssl rsa -in ./ronaldoold.key -out ./ronaldonew.key

5, HTTPS service optimization

    1. Activating KeepAlive Long Links

      • In configuration file write:keepalive_timeout 100

    2. Set the SSL session cache

      • In configuration file write:ssl_session_cache shared:SSL:10m

Five, the development of Nginx and LUA

Nginx+lua Advantages:
Full combination of Nginx's concurrent processing Epoll advantages and LUA's lightweight implementation of simple functions and high concurrency scenarios.

1. Lua

is a concise, lightweight, extensible scripting language
    1. Installation:yum install lua

    2. Run:

      • luacommand into the interactive interface, enter: print("Hello World") can

      • Execute the LUA script:

#!/usr/bin/luaprint ("Hello World")
    1. Comments

      • --line Comment

      • --[[block Comment--]

    2. Variable

      • A = ' alon123 '

      • A = "alon123" "

      • A = ' 97lo1004923 '

      • A = [[Alo

      • 123 "]

      • The above is the same meaning, the 3rd is the ASCII table

Attention:
LUA numeric types have only double types
Lua Boolean type only nil and false is false, number 0, empty string is True
If the variables in LUA are not specified, they are all global variables; If you want to be a local variable, the signature will be added local
LUA does not operate with + + or + =
~=: Not equal to
.. : string concatenation
Read and write functions read and write from stdin and stdout, respectively, for IO libraries
    1. While Loop statement

sum = 0num = 1while num <= do    sum = sum + num    num = num + 1endprint ("sum =", sum)
    1. For Loop statement

sum = 0for i = 1,100 do    sum = sum + iend
    1. If-else Judgment Statement

if age = = and sex = = "Male" then    print ("Men greater than 40 years old") ElseIf age>60 and sex ~= "Female" then    print ("non-women and greater than") E LSE    Local Age = Io.read ()    print ("Your.") Age) End

2. Nginx + LUA Environment

    1. Required Downloads and Installation:

      1. Luajit

      2. Ngx_devel_kit and Lua-nginx-module

      3. Re-compiling Nginx

      4. For detailed download and installation procedures See:

3, Nginx call LUA module instructions

nginx pluggable Modular load execution, total 11 processing stages
instruction meaning
Set_by_lua,set_by_lua_file Set nginx variable to implement complex assignment logic
Access_by_lua,access_by_lua_file Request access phase processing, for access control
Content_by_lua,content_by_lua_file Content processor, receiving request processing and outputting response

4. Nginx Lua API

API meaning
Ngx.var Nginx variable
Ngx.req.get_headers Get Request Header
Ngx.req.get_uri_args Get URL Request parameters
Ngx.redirect redirect
Ngx.print Output Response content Body
Ngx.say Same nginx.print, but will enter.
Ngx.header Output response Header
...

5. Grayscale Publishing

according to a certain relationship between the code to go online, so that the release of the code can smoothly transition online.
    • According to the user's information cookie and other information differences

    • Based on the user's IP address

Implementing Grayscale Publishing:

Related recommendations:

The scene practice of Nginx

About Nginx's basic content

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.