The basic configuration common Nginx (III)

  Earlier we talked at the Nginx as a WEB server to client requests configuration, file operations optimization, Nginx access control, basic verification ,, state module status page, gzip compression configuration; review Refer https://www.cnblogs.com /qiuhom-1874/p/12381331.html ; today we chat log module, ssl module, rewrite module;

  A, ngx_http_log_module: the role of this module is designated nginx access log format;

    log_format name [escape = default | json | none] string ...; This command is used to define the format of the access log ngxin, wherein this parameter allows escape escaping disposed in a variable json or the default character, use the default forwarding default justice, none expressed prohibition of escape. You can use string variables nginx core modules and other embedded module; Note that this command is only used in http configuration section for custom log format, the face of all the virtual host can be defined when defining call log file log format ;

    access_log path [format [buffer = size] [gzip [= level]] [flush = time] [if = condition]]; Specifies the path to the log file, wherein the log buffer = size represents the specified buffer size, gzip = level represents a specified log compression level, fulsh = time specified log indicate how often the log buffer memory to put the contents of the file to disk;

  Example:

   Note: The above configuration means that the definition of a log format whose name is main, rear enclosed in single quotes part is caused by the contents of the log format, which means that the client ip $ remote_addr this value is not necessarily the client ip, this depends on the application environment, if in front of nginx server has a proxy server, this variable will record the front-end proxy ip, if nginx is directly to the client, then this value is to record the client ip, ip specific it recorded that this depends on the application environment; $ remote_user when remote user, if the site we configurations have proven, then this value is the record of a user name for authentication, if there is no default is "-"; $ time_local represent local server time; $ request representation by the client requests a resource path, and http protocol version; $ record variable status response status code client requests a server resource; bytes $ body_bytes_sent body response variable recorded client access server, in response to the number of bytes does not include a head; this variable record $ http_referer referer client letter ; Http referer header is part of the client browser to access the web server under normal circumstances, this would bring the referer information, the purpose is to tell the server that this request is a link from that page over; $ http_user_agent This variable record customer will bring this information User_Agent information terminal, http head User_Agent also part of the client accessing the web server, the purpose is to tell the server operating system type, version, browser information and other clients; $ http_x_forwarded_for this variable is used to record the client real IP, if the client is accessing the server through a proxy, then this value is not recorded IP proxy client, but the client real IP information; more built-in variables can refer http://nginx.org/en/docs/ http / ngx_http_core_module.html # variables

  Well defined above log format, we can specify where the log file path and log format explicitly with our definition of "main" through access_log, when we have a browser to access the web server, the server will be recorded in our definition format log, as shown below

     open_log_file_cache max = N [inactive = time ] [min_uses = N] [valid = time]; specified cache metadata information related to each log file; where max = N represents a maximum number of file descriptors cache, if it is filled with the LRU clean the cache algorithm; inactive = time indicates when the specified length of inactivity, by default, 10 seconds; min_user = N represents inactive when accessing the specified length is greater than or equal to this value as the only active items ;; vaild = time specified test positive each cache entry in the cache if the time interval active item;

  Two, ngx_http_ssl_module: This module implements nginx web-based services offer https

    ssl on | off; ssl enable or disable the function

    ssl_certificate file; set the current virtual host certificate

    ssl_certificate_key file; set the current virtual host certificate private key file

    ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2]; support ssl protocol version, the default is three;

    ssl_session_cache off | none | [builtin [: size]] [shared: name: size]; which builtin [: size] represents the use OpenSSL built-in cache, this cache for each worker process private; [shared: name: size]: It represents a shared cache among worker;

    ssl_session_timeout time; client-side connector may be multiplexed with an effective long-ssl session cache ssl parameters buffered;

  Example:

    Make https server nginx work, we need to apply for their certificate, the relevant CA server set up, as well as certificate application information, refer to the relevant principles https://www.cnblogs.com/qiuhom-1874/p/12237944.html , here said process next, we need to prepare a CA (may be the machine), and then generate a certificate request file on nginx server, and then sends the file to the CA server and CA server issue a certificate application documents to generate the corresponding certificate, then CA to issue the signed certificate file server nginx, and nginx server configured to use the certificate to get a certificate in the configuration file, of course, the above steps can also be done directly on the CA, and finally sends the generated private key file and certificate nginx to the server, into the next process;

    1, set up CA, is actually very simple, so-called CA is to generate a self-signed certificate can

[root@test ~]# cd /etc/pki/CA/
[root@test CA]# tree
.
├── certs
├── crl
├── newcerts
└── private

4 directories, 0 files
[root@test CA]# (umask 077;openssl genrsa -out private/cakey.pem 2048)
Generating RSA private key, 2048 bit long modulus
...+++
...................+++
e is 65537 (0x10001)
[root@test CA]# tree
.
├── certs
├── crl
├── newcerts
└── private
    └── cakey.pem

4 directories, 1 file
[root@test CA]#

  Note: The above is generated CA private key

  2, generate a self-signed certificate

[root@test CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 3650
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:SICHUAN
Locality Name (eg, city) [Default City]:GUANGYUAN
Organization Name (eg, company) [Default Company Ltd]:TEST
Organizational Unit Name (eg, section) []:DEVOPS
Common Name (eg, your name or your server's hostname) []:ca.ilinux.io
Email Address []:
[root@test CA]# touch index.txt
[root@test CA]# echo 01 >serial
[root@test CA]# tree
.
├── cacert.pem
├── certs
├── crl
├── index.txt
├── newcerts
├── private
│ └── cakey.pem
└── serial

4 directories, 4 files
[root@test CA]# 

  Tip: this CA is ready

  3, ready to nginx server certificate private key and certificate request file server

[root@www ~]# mkdir /etc/nginx/ssl
[root@www ~]# cd /etc/nginx/ssl
[root@www ssl]# ls
[root@www ssl]# (umask 077;openssl genrsa -out nginx.key 2048)
Generating RSA private key, 2048 bit long modulus
.........................................+++
.......+++
e is 65537 (0x10001)
[root@www ssl]# ll
total 4
-rw------- 1 root root 1679 Mar  2 23:06 nginx.key
[root@www ssl]# openssl req -new -key nginx.key -out nginx.csr 
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:SICHUAN
Locality Name (eg, city) [Default City]:GUANGYUAN
Organization Name (eg, company) [Default Company Ltd]:TEST
Organizational Unit Name (eg, section) []:DEVOPS
Common Name (eg, your name or your server's hostname) []:www.ilinux.io
Email Address []:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
[root@www ssl]# ll
total 8
-rw-r--r-- 1 root root 1009 Mar  2 23:07 nginx.csr
-rw------- 1 root root 1679 Mar  2 23:06 nginx.key
[root@www ssl]#

  Tip: Certificate Request file to this nginx server to do the work, we just need to send the application documents to the CA

[root@www ssl]# scp -P 41319 nginx.csr [email protected]:/tmp/
[email protected]'s password: 
nginx.csr                                                     100% 1009   225.4KB/s   00:00    
[root@www ssl]# 

  Tip: If you did not work in the SSH standard port, need to use -P (uppercase) when using scp command to specify the ssh port

  4, CA certificate issued nginx

[root@test CA]# openssl ca -in /tmp/nginx.csr -out certs/nginx.pem -days 365
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Mar  2 15:11:02 2020 GMT
            Not After : Mar  2 15:11:02 2021 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = SICHUAN
            organizationName          = TEST
            organizationalUnitName    = DEVOPS
            commonName                = www.ilinux.io
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA: FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                F7: 76: 62: 31: 04: D8: CE: 0E: 6E: CD: C5: 14: 05: EF: 7F: E4: A5: AD: A0: 91
            X509v3 Authority Key Identifier: 
                keyid: D5: 61: A5: 2F: BF: 67: 51: 78: D7: 5D: F8: 51: F4: 3C: FB: 22: F9: E5: A7: 3B

Certificate is to be certified until Mar  2 15:11:02 2021 GMT (365 days)
Sign the certificate? [Y / n]: and


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
[root@test CA]# tree
.
├── cacert.pem
├── certs
│ └── nginx.pem
├── crl
├── index.txt
├── index.txt.attr
├── index.txt.old
├── newcerts
│ └── 01.pem
├── private
│ └── cakey.pem
├── serial
└── serial.old

4 directories, 9 files
[root@test CA]# 

  Tip: We just need a signed certificate to the server to nginx

[root@test CA]# scp certs/nginx.pem 192.168.0.30:/etc/nginx/ssl/
The authenticity of host '192.168.0.30 (192.168.0.30)' can't be established.
ECDSA key fingerprint is SHA256:EG9nua4JJuUeofheXlgQeL9hX5H53JynOqf2vf53mII.
ECDSA key fingerprint is MD5:57:83:e6:46:2c:4b:bb:33:13:56:17:f7:fd:76:71:cc.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.0.30' (ECDSA) to the list of known hosts.
[email protected]'s password: 
nginx.pem                                                             100% 4464     2.1MB/s   00:00    
[root@test CA]# 

  Tip: CA this work is complete, then we directly use the certificate configuration ngxin directly on the server nginx

[root@www conf.d]# cat login.conf 
server {
        listen 443 ssl;
        server_name 192.168.0.30;
        root /data/web/html;
        gzip on;
        gzip_types text/xml text/plain;
        gzip_disable Firefox;
        location /basic_status {
                stub_status;
                auth_basic "please input you username and passwd login";
                auth_basic_user_file /etc/nginx/conf.d/.ngxpasswd;
        }
        ssl_certificate "/etc/nginx/ssl/nginx.pem";
        ssl_certificate_key "/etc/nginx/ssl/nginx.key";
        ssl_protocols sslv2 sslv3 tlsv1 tlsv1.1 tlsv1.2;
        ssl_session_cache shared:SSL:10m;


}
[root@www conf.d]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@www conf.d]# nginx -s reload
[root@www conf.d]# 

  Verification: use a browser to access a look at our credentials configuration is in effect

   Tip: appears normal on this interface, because our own CA is set up, the default browser do not know, we can put the CA certificate into the browser will not have this problem, then we put CA certificate into the browser bar

  Need to change the default windows are identified by file extension, so the CA certificate onto the rear windows for the .crt suffix can: prompt.

  导入CA的证书后,我们再来用浏览器访问下我们的网站是否还会提示不是私密连接呢?

 

  我们导入CA证书后,我们重新打开浏览器访问网站,就没有提示不是私密连接了,同时我们访问我们网站也是基于https访问,不再是http;以上就是nginx工作成https服务器搭建过程;

   三、ngx_http_rewrite_module:此模块用于使用PCRE正则表达式查找匹配用户请求的URI,返回重定向和有条件地选择配置来更改请求URI。本质上就是查找替换的过程,用户请求的url通过正则匹配,然后用其他url或uri进行替换,随后把新的url或uri返回给客户端,由客户端重新对新的URL或URI发送请求;

  1、rewrite regex replacement [flag]:将用户请求的URI基于regex所描述的模式进行检查,匹配到时将其替换为replacement指定的新的URI;注意:如果在同一级配置块中存在多个rewrite规则,那么会自上而下逐个检查;被某条件规则替换完成后,会重新一轮的替换检查,因此,隐含有循环机制;[flag]所表示的标志位用于控制此循环机制;如果replacement是以http://或https://开头,则替换结果会直接以重向返回给客户端;其中flag有四种,last表示重写完成后停止对当前URI在当前location中后续的其它重写操作,而后对新的URI启动新一轮重写检查;提前重启新一轮循环; 这个也是默认行为,有点类似continue指令的意思,不退出循环,只是退出当次循环,提前进入下次循环;break表示重写完成后停止对当前URI在当前location中后续的其它重写操作,而后直接跳转至重写规则配置块之后的其它配置;结束循环;这个我们可以理解为循环里的break指令,直接跳出循环,进行下面的配置指令;redirect表示重写完成后以临时重定向方式直接返回重写后生成的新URI给客户端,由客户端重新发起请求;不能以http://或https://开头;permanent表示重写完成后以永久重定向方式直接返回重写后生成的新URI给客户端,由客户端重新发起请求;这四个值的区别是,前两个浏览器上都看不到跳转(用户是看不到明确的跳转),后两者者看得到;

  示例:

rewrite /(.*)$ https://www.ilinux.io/basic_status;

  提示:以上配置表示客户端访问我们服务器的任何uri都给重写为https://www.ilinux.io/basic_status这个url

  提示:之所以能够看到302的响应码是因为我们在规则里把用户的rul重写成https://www.ilinux.io/basic_status ,浏览器看到重写后的URL是以https开头的,它就会拿着这个url去请求新的URL,所以我们这里可以看到302响应码;

   提示:以上配置表示,用户访问.jpg结尾的URL时,我们都对它重写为访问/test/test.html

  提示:我们对用户请求的url进行替换时,没有用到http或https去替换时,我们在浏览器上是看不到后面浏览器重新对新的url发起请求的请求信息,这是我们重写规则默认使用了last,last和break如果都不以http或https去替换用户的rul,在浏览器是看不到跳转的响应码,要想看到该过程我们可以在后面加redirect或者permanent,它俩的区别在于,一个是临时重定向,响应码是302,一个是永久重定向响应码是301;如下

 rewrite /(.*)\.jpg  /test/ redirect;

  提示:我们只在上面的配置上在rewrite规则上加了一个redirect标记,加上它,浏览器就会对新的uri发起新的请求,如下

  2、return:停止处理并将指定的响应码或URL返回给客户端

    return code [text];表示返回状态码或简短原因短语

    return code URL;返回状态码和url

    return URL;返回url

  3、rewrite_log on | off;是否开启重写日志

  4、if(condition) {……};引入一个新的配置上下文;条件满足时执行配置块中的配置指令;可用在server和location配置段中;这里的条件可以是变量,如果变量是字符串,非空为真,空为假;如果变量是数字则非0为真,0为假;当然条件也可以是一个比较表达式,所谓表达式就是由操作符连接起来的式子,常用的操作符有比较操作符,文件及目录存在性判断;比较操作符有:== 、!= 、~表示模式匹配,区分字符大小写;~*表示模式匹配,不区分字符大小写;!~表示模式不匹配,区分字符大小写;!~*表示模式不匹配,不区分字符大小写;文件及目录存在性判断的有 -e,!-e、-f,!-f、-d,!-d,、-x,!-x,这里的文件或目录存在性判断同shell里面的文件或目录存在性判断是一样的;

  5、set $variable value;设置用户指定以变量;

  示例:

if ($http_user_agent ~ MSIE) {
    rewrite ^(.*)$ /msie/$1 break;
}

if ($http_cookie ~* "id=([^;]+)(?:;|$)") {
    set $id $1;
}

if ($request_method = POST) {
    return 405;
}

if ($slow) {
    limit_rate 10k;
}

if ($invalid_referer) {
    return 403;
}

  提示:第一个if表示判断用户浏览器类型,如果匹配MSIE 则进行url重写,重写为/msie/$1 ,这里的$1表示rewrite规则里匹配到第一个括号里的内容的引用,和sed命令里的\1类似;第二个if表示判断变量$http_cookie 里的值是否匹配后面的正则表达式,如果匹配则设置$id变量的值为$1,这里的$1表示正则表达式里括号分组匹配到的内容;第三个if表示判断用户请求的方法是否是POST,如果是就返回405,意思就是不让用户用POST方法提交数据;第五个if表示判断$slow是否为空,不为空就设置limit_rate 10k,意思就是如果$slow的值为真,则限制客户端的响应;最后一个if表示判断$invalid_referer 是否为空,为空表示没有非法的referer,没有非法referer就不做处理,如果有非法referer,即不为空,则返回403,这是一个防盗链的配置;通常我们要先定义合法的referer,然后再来判断非法referer来实现防盗链(定义了合法的referer后相对的不在合法的referer列表里就表示非法的referer);合法referer的定义可以用valid_referers来指定;

Guess you like

Origin www.cnblogs.com/qiuhom-1874/p/12398242.html