current position:Home>7.Nginx_ module
7.Nginx_ module
2021-08-25 09:53:42 【Little monster 55】
1.ngx_http_log_module modular
Specify log format to record requests
log_format name string ...;
string have access to nginx Variables embedded in core modules and other modules
access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
access_log off; # Disable access log
Access log file path , Format and associated buffer configuration
buffer=size
flush=time
Example
log_format compression '$remote_addr-$remote_user [$time_local] '
'"$request" $status $bytes_sent '
'"$http_referer" "$http_user_agent" "$gzip_ratio"';
access_log /spool/logs/nginx-access.log compression buffer=32k;
Customize json Log format
nginx The content of the default access log is relatively simple , The default format is not convenient for later log statistical analysis , In a production environment, there is usually nginx Log to json journal , And then use it with ELK Do log collection - Statistics - analysis
json Example of access log in format :
{"@timestamp":"2019-02-
22T08:55:32+08:00","host":"192.168.7.102","clientip":"192.168.0.1","size":162,"resp
onsetime":0.000,"upstreamtime":"-","upstreamhost":"-
","http_host":"www.magedu.net","uri":"/favicon.ico","domain":"www.magedu.net","xff"
:"-","referer":"-","tcp_xff":"","http_user_agent":"Mozilla/5.0 (Windows NT 6.1;
Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0","status":"404"}
log_format access_json '{"@timestamp":"$time_iso8601",'
'"host":"$server_addr",'
'"clientip":"$remote_addr",'
'"size":$body_bytes_sent,'
'"responsetime":$request_time,'
'"upstreamtime":"$upstream_response_time",'
'"upstreamhost":"$upstream_addr",'
'"http_host":"$host",'
'"uri":"$uri",'
'"domain":"$host",'
'"xff":"$http_x_forwarded_for",'
'"referer":"$http_referer",'
'"tcp_xff":"$proxy_protocol_addr",'
'"http_user_agent":"$http_user_agent",'
'"status":"$status"}';
access_log /apps/nginx/logs/access_json.log access_json;
json Log access statistics in format
#cat nginx_json.py
#!/usr/bin/env python
#coding:utf-8
status_200= []
status_404= []
with open("access_json.log") as f:
for line in f.readlines():
line = eval(line)
if line.get("status") == "200":
status_200.append(line.get)
elif line.get("status") == "404":
status_404.append(line.get)
else:
print(" Status code ERROR")
f.close()
print " Status code 200 There are --:",len(status_200)
print " Status code 404 There are --:",len(status_404)
# python nginx_json.py
Status code 200 There are --: 1910
Status code 404 There are --: 13
open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];
open_log_file_cache off;
Cache the metadata information related to each log file
max: Maximum number of file descriptors to cache
min_uses: stay inactive If the access value is greater than or equal to this value in the specified duration, it can be regarded as an active item
inactive: The length of inactivity
valid: Time interval to verify whether each cache item in the cache is active
favicon.ico File is the icon displayed when the browser collects the web address , When using a browser to access a page , The browser will initiate a request to get the page itself favicon.ico file , But when the browser requests favicon.ico When the file does not exist , The server will record 404 journal , And the browser will show 404 Report errors
Solution :
The server does not record access logs :
location = /favicon.ico {
log_not_found off; # No events found in the file are not recorded error_log
access_log off; # Don't record access_log
}
Save the icon to the specified directory to access :
#location ~ ^/favicon\.ico$ {
location = /favicon.ico {
root /data/nginx/html/pc/images;
}
2.ngx_http_gzip_module
use gzip Method to compress response data , Save bandwidth
gzip on | off;
Enable or disable gzip Compress
gzip_comp_level level;
Compression ratio from low to high :1 To 9, Default :1
gzip_disable regex ...;
Matching to the client browser does not perform compression
Example :gzip_disable "MSIE[1-6]\.";
gzip_min_length length;
The response packet size threshold for compression enabled
gzip_http_version 1.0 | 1.1;
Set when compression is enabled , Minimum version of the protocol , Default :1.1
gzip_buffers number size;
The number of buffers and the size of each buffer when compression is supported
Default :32 4k or 16 8k
gzip_types mime-type ...;
Indicates which types of resources are compressed only ; Compression filter
The default package contains text/html, You don't need to display the specified , Otherwise mistakes
gzip_vary on | off;
If compression is enabled , Whether to insert at the head of the response message “Vary: Accept-Encoding”
gzip_proxied off | expired | no-cache | no-store | private | no_last_modified | no_etag | auth | any ...;
nginx When acting as a proxy server , The response message to the back-end server , Under what conditions can compression be enabled
off: Do not enable compression
expired,no-cache, no-store,private: The header of the response message to the back-end server Cache-Control It's worth any one , Enable compression
Example :
gzip on;
gzip_comp_level 6;
gzip_min_length 64;
gzip_vary on;
gzip_types text/xml text/css application/javascript;
3.SSL Certificate brand (CA supplier )
Alibaba cloud SSL The certificate application :
https://www.aliyun.com/product/cas?spm=a2c4g.11174283.2.1.47676fd4baNCYX
Support Alibaba cloud to issue digital certificates CA The center includes :
Symantec: symantec (Symantec) It is the world's largest digital certification authority 、 The world's most trusted SSL Certificate brand , All certificates use industry-leading encryption technology , Provide security solutions for different websites and servers
CFCA: China Financial Certification Center (CFCA) Through international WebTrust authentication , Follow the global unified assurance standards , It's international CA Members of the browser Alliance .CFCA Global trust SSL certificate , It is independently developed by China's authoritative digital certificate certification authority , Pure domestic certificate .CFCA Provide 7x24 Hours of financial security services , And there is a perfect risk underwriting plan . Provide Chinese version of global trust system electronic authentication business rules (CPS), It is convenient for users to understand the rights and obligations of both parties
GeoTrust: GeoTrust It is the second largest digital certification authority in the world , He is also a leader in identity authentication and trust authentication , Using a variety of advanced technologies, organizations and companies of any size can safely 、 Low cost local deployment SSL Digital certificate and realize various identity authentication
GlobalSign: GMO GlobalSign It is one of the earliest digital certificate certification institutions in the world , Has been committed to network security authentication and digital certificate services , Is a trusted CA and SSL Digital certificate providers
Alibaba cloud cooperates with qualified CA The center recommends the following digital certificate configuration combinations :
Free DV SSL: Free DV SSL The certificate is basic SSL product
explain At present, only Symantec Provide free digital certificate , This certificate only supports binding one domain name
Only verify domain name ownership , In a matter of hours
Only the communication link encryption function is provided
The root certificate generally uses CA The root certificate of the Certification Center
Support binding a detailed subdomain name , Wildcard domain names are not supported
wildcard DV SSL: wildcard DV SSL The certificate belongs to DV type SSL certificate (Domain Validation SSL)
Only verify domain name ownership , In a matter of hours
Provide high-strength communication link encryption function
Support binding a domain name with wildcards
pro OV SSL: pro OV SSL The certificate belongs to OV type SSL certificate (Organization Validation SSL)
Verify the ownership of the domain name and the true identity of the applicant , Solve the problem of online trust
The applicant's business unit name is displayed in the certificate , Let access users feel at ease
Provide high-strength communication link encryption function
Supports up to binding 100 Domain names , Support binding wildcard domain name
explain Except the Professional Edition OV SSL Outside the certificate ,Symantec It also provides enhanced OV SSL certificate . Enhanced OV SSL The certificate adopts ECC Elliptic curve algorithm
premium EV SSL: premium EV SSL The certificate belongs to EV type SSL certificate (Extended Validation SSL)
Strictly verify the ownership of the domain name and the true identity of the applicant
The certificate can display a green address bar in most browsers ( Some certificates are in Safari It doesn't show in the browser ), Effectively solve the problems of online trust and website counterfeiting
The certificate displays the applicant's business unit information in detail , Let access users feel at ease
Provide high-strength communication link encryption function .
Supports up to binding 100 Domain names
explain Except Advanced Edition EV SSL Outside the certificate ,Symantec It also provides enhanced EV SSL certificate . Enhanced EV SSL The certificate adopts ECC Elliptic curve algorithm
4.ngx_http_ssl_module modular :
ssl on | off;
Enable... For the specified virtual machine HTTPS protocol, Suggest using listen Instruction substitution
ssl_certificate file;
The current virtual host uses PEM Form of certificate file
ssl_certificate_key file;
The private key file on the current virtual host that matches its certificate
ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2]; Support ssl Protocol version , Default to the last three
ssl_session_cache off | none | [builtin[:size]] [shared:name:size];
none: Notify client support ssl session cache, But it doesn't support
builtin[:size]: Use OpenSSL Built in cache , For each worker Process private
[shared:name:size]: In each worker Using a shared cache between
ssl_session_timeout time;
Client connections can be reused ssl session cache Effective length of cache in , Default 5m
Example :
server {
listen 443 ssl;
server_name www.magedu.com;
root /vhosts/ssl/htdocs;
ssl on;
ssl_certificate /etc/nginx/ssl/nginx.crt;
ssl_certificate_key /etc/nginx/ssl/nginx.key;
ssl_session_cache shared:sslcache:20m;
ssl_session_timeout 10m;
}
5.ngx_http_rewrite_module modular :
Will be requested by the user URI be based on PCRE regex The described pattern is checked , Then complete the redirection replacement
Example :
http://www.magedu.com/hn --> http://www.magedu.com/henan
http://www.magedu.com --> https://www.magedu.com/
if (condition) { ... }
When conditions are met , Execute the configuration instructions in the configuration block ;server, location
condition:
Comparison operator :
= identical != Different
~ Pattern matching , Case sensitive
~* Pattern matching , Do not case sensitive characters
!~ Pattern mismatch , Case sensitive
!~* Pattern mismatch , Do not case sensitive characters
File and directory existence judgment :
-e,!-e Existence or not ( Including documents , Catalog , Soft link )
-f,!-f file -d,!-d Catalog -x,!-x perform
Be careful : if (condition) { ... } In the sentence , If $ The value of the variable is an empty string or in the form of 0 Any string at the beginning , be if The directive considers this condition to be false, Other conditions are true
Example :
location /test {
index index.html;
default_type text/html;
if ( $scheme = http ){
return 301 https://www.magedu.net/;
}
if ( $scheme = https ){
echo "if ----> $scheme";
}
Example :
if (-f $request_filename) {
echo "file is exist";
}
if (!-f $request_filename) {
echo "file is not exist";
return 409;
}
return
return code [text]; # Returns the status code and text description specified by the client
return code URL;
return URL;
Stop processing , And return the response code specified by the client ( Include : 204, 400, 402 — 406, 408, 410, 411, 413, 416, 500 — 504), Also on 301, 302, 303, 307, 308 Jump to URL
rewrite_log on | off;
Whether to open the rewrite log , Sent to the error_log(notice level)
set $variable value;
User defined variables
Be careful : Variable definition and call should be based on $ start
Example :
location /test {
root /data/nginx/html/pc;
default_type text/html;
index index.html;
if ( $scheme = http ){
#return 666;
#return 666 "not allow http";
#return 301 http://www.baidu.com;
return 500 "service error";
echo "if-----> $scheme"; #return The following will no longer execute
}
if ( $scheme = https ){
echo "if ----> $scheme";
}
rewrite regex replacement [flag]
Will be requested by the user URI be based on regex The described pattern is checked , Replace it with replacement Designated new URI
Be careful : If there are more than one configuration block at the same level rewrite The rules , Then it's going to be checked one by one from the top down ; After being replaced by a conditional rule , There will be a new round of replacement checks
There is a circular mechanism , But not more than 10 Time ; If exceeded , Tips 500 Response code ,[flag] The flag bit represented is used to control the loop mechanism
If replacement In order to http:// or https:// start , The replacement result will be returned directly to the client in a retransmission , Permanent redirection 301
[flag]:
last: When the rewrite is complete, stop the current URI At present location Other subsequent rewriting operations in , And then to the new URI Start a new round of rewrite checking ; Restart a new cycle ahead of time
break: When the rewrite is complete, stop the current URI At present location Other subsequent rewriting operations in , Then directly jump to other configurations after the rewrite rule configuration block ; End of cycle
redirect: Temporary redirection , After rewriting, it will directly return the new generated after rewriting in the way of temporary redirection URI To the client , The client restarts the request ; Relative paths can be used , or http:// or https:// start , This redirection information is not cacheable , Status code :302
permanent: After the completion of the rewriting, it will directly return the new generated after rewriting in the way of permanent redirection URI To the client , The client restarts the request , This redirection information can be cached , Status code :301
break: After successful matching, no downward matching is allowed , It won't jump to other location, That is, end the matching directly and return the result data to the client
last: To someone location Of URL After the match is successful, the current... Will be stopped location Subsequent to rewrite The rules , And end the present location, Then match the generated new URL Jump to other location Continue matching , Until there is no location After matching, it will be the last time location The data is returned to the client
location /break {
rewrite ^/break/(.*) /test/$1 break; #break Will not jump to other location
return 666 "break";
}
location /last {
rewrite ^/last/(.*) /test/$1 last; #last Will jump to other location Continue matching new URI
return 888 "last";
}
location /test {
return 999 "test";
index index.html;
root /data/nginx;
}
mkdir /data/nginx/test/
echo test Page > /data/nginx/test/index.html
requirement : take http:// Request to jump to https://
Production cases
location / {
if ($scheme = http ) {
rewrite / https://www.magedu.net/ redirect;
}
}
requirement : When the user visits the company's website, he enters an incorrect URL, You can redirect users to the home page of the official website
Production cases
location / {
root /data/nginx/html/pc;
index index.html;
if (!-f $request_filename) {
#return 404 "No exsit";
rewrite (.*) http://www.magedu.net/index.html;
}
}
6.ngx_http_referer_module modular :
Used to prevent Referer The first request access without a valid value , To prevent chain theft
valid_referers none|blocked|server_names|string ...;
Definition referer The legal available value of the header , What cannot be matched will be illegal values
none: The header of the request message does not have referer The first one
blocked: The request message has referer The first one , But there is no valid value
server_names:referer The header contains the host name
arbitrary_string: Any string , But it can be used * As a wild card
regular expression: The string to which the specified regular expression pattern matches , To use ~ start , for example : ~.*\.magedu\.com
Prevent chain theft production cases :
valid_referers none block server_names
*.magedu.com magedu.* *.mageedu.com mageedu.* ~\.magedu\. ~\.google\. ~\.baidu\.;
if ($invalid_referer) {
return 403 "Forbidden Access";
}
copyright notice
author[Little monster 55],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210825095336556z.html
The sidebar is recommended
- Crazy blessing! Tencent boss's "million JVM learning notes", real topic of Huawei Java interview 2020-2021
- JS JavaScript how to get the subscript of a value in the array
- How to implement injection in vuex source code?
- JQuery operation select (value, setting, selected)
- One line of code teaches you how to advertise on Tanabata Valentine's Day - Animation 3D photo album (music + text) HTML + CSS + JavaScript
- An article disassembles the pyramid architecture behind the gamefi outbreak
- BEM - a front-end CSS naming methodology
- [vue3] encapsulate custom global plug-ins
- Error using swiper plug-in in Vue
- Another ruthless character fell by 40000, which was "more beautiful" than Passat and maiteng, and didn't lose BMW
guess what you like
-
Huang Lei basks in Zhang Yixing's album, and the relationship between teachers and apprentices is no less than that in the past. Netizens envy Huang Lei
-
He was cheated by Wang Xiaofei and Li Chengxuan successively. Is an Yixuan a blessed daughter and not a blessed home?
-
Zhou Shen sang the theme song of the film "summer friends and sunny days" in mainland China. Netizen: endless aftertaste
-
Pink is Wangyuan online! Back to the peak! The new hairstyle is creamy and sassy
-
Front end interview daily 3 + 1 - day 858
-
Spring Webflux tutorial: how to build reactive web applications
-
[golang] walk into go language lesson 24 TCP high-level operation
-
August 23, 2021 Daily: less than three years after its establishment, Google dissolved the health department
-
The female doctor of Southeast University is no less beautiful than the female star. She has been married four times, and her personal experience has been controversial
-
There are many potential safety hazards in Chinese restaurant. The top of the program recording shed collapses, and the artist will fall down if he is careless
Random recommended
- Anti Mafia storm: He Yun's helpless son, Sun Xing, is destined to be caught by his dry son
- Introduction to flex flexible layout in CSS -- learning notes
- CSS learning notes - Flex layout (Ruan Yifeng tutorial summary)
- Today, let's talk about the arrow function of ES6
- Some thoughts on small program development
- Talk about mobile terminal adaptation
- Unwilling to cooperate with Wang Yibo again, Zhao Liying's fans went on a collective strike and made a public apology in less than a day
- JS function scope, closure, let, const
- Zheng Shuang's 30th birthday is deserted. Chen Jia has been sending blessings for ten years. Is it really just forgetting to make friends?
- Unveil the mystery of ascension
- Asynchronous solution async await
- Analysis and expansion of Vue infinite scroll source code
- Compression webpack plugin first screen loading optimization
- Specific usage of vue3 video play plug-in
- "The story of huiyeji" -- people are always greedy, and fairies should be spotless!
- Installing Vue devtool for chrome and Firefox
- Basic usage of JS object
- 1. JavaScript variable promotion mechanism
- Two easy-to-use animation JS that make the page move
- Front end Engineering - scaffold
- Java SQL Server intelligent fixed asset management, back end + front end + mobile end
- Mediator pattern of JavaScript Design Pattern
- Array de duplication problem solution - Nan recognition problem
- New choice for app development: building mobile applications using Vue native
- New gs8 Chengdu auto show announces interior Toyota technology blessing
- Vieira officially terminated his contract and left the team. The national security club sent blessings to him
- Less than 200000 to buy a Ford RV? 2.0T gasoline / diesel power, horizontal bed / longitudinal bed layout can be selected
- How does "heart 4" come to an end? Pinhole was boycotted by the brand, Ma Dong deleted the bad comments, and no one blessed him
- We are fearless in epidemic prevention and control -- pay tribute to the front-line workers of epidemic prevention!
- Front end, netty framework tutorial
- Xiaomi 11 | miui12.5 | android11 solves the problem that the httpcanary certificate cannot be installed
- The wireless charging of SAIC Roewe rx5 plus is so easy to use!
- Upload and preview pictures with JavaScript, and summarize the most complete mybatis core configuration file
- [25] typescript
- CSS transform Complete Guide (Second Edition) flight.archives 007
- Ajax foundation - HTTP foundation of interview essential knowledge
- Cloud lesson | explain in detail how Huawei cloud exclusive load balancing charges
- Decorator pattern of JavaScript Design Pattern
- [JS] 10. Closure application (loop processing)
- Left hand IRR, right hand NPV, master the password of getting rich