nginx

1.nginx配置步骤

安装163源

[root@linfan ~]#cd /etc/yum.repos.d/
[root@linfan yum.repos.d]# mv * /tmp/
[root@linfan yum.repos.d]# curl -o 163.repo http://mirrors.163.com/.help/CentOS7-Base-163.repo
[root@linfan yum.repos.d]# sed -i 's/\$releasever/7/g' /etc/yum.repos.d/163.repo
[root@linfan yum.repos.d]# sed -i 's/enabled=0/enabled=1/g' /etc/yum.repos.d/163.repo
[root@linfan yum.repos.d]# yum clean all
[root@linfan yum.repos.d]# yum -y install gcc gcc-c++
[root@linfan yum.repos.d]# yum -y install wget

创建系统用户nginx

[root@linfan ~]# useradd -r -M -s /sbin/nologin nginx 

安装依赖环境

[root@linfan ~]# yum -y install pcre-devel openssl openssl-devel gd-devel   
[root@linfan ~]# yum -y groups mark install 'Development Tools'
Loaded plugins: fastestmirror
There is no installed groups file.
Maybe run: yum groups mark convert (see man yum)
Loading mirror speeds from cached hostfile
Marked install: Development Tools
[root@linfan ~]# yum grouplist
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
Available Environment Groups:
   Minimal Install
   Compute Node
   Infrastructure Server
   File and Print Server
   Basic Web Server
   Virtualization Host
   Server with GUI
   GNOME Desktop
   KDE Plasma Workspaces
   Development and Creative Workstation
Installed Groups:
   Development Tools
Available Groups:
   Compatibility Libraries
   Console Internet Tools
   Graphical Administration Tools
   Legacy UNIX Compatibility
   Scientific Support
   Security Tools
   Smart Card Support
   System Administration Tools
   System Management
Done

创建日志存放目录

[root@linfan ~]# mkdir -p /var/log/nginx
[root@linfan ~]# chown -R nginx.nginx /var/log/nginx

下载nginx

[root@linfan ~]# cd /usr/src/
[root@linfan src]# wget http://nginx.org/download/nginx-1.14.0.tar.gz
--2018-08-30 06:35:21--  http://nginx.org/download/nginx-1.14.0.tar.gz
Resolving nginx.org (nginx.org)... 95.211.80.227, 206.251.255.63, 2606:7100:1:69::3f, ...
Connecting to nginx.org (nginx.org)|95.211.80.227|:80... connected.
HTTP request sent, awaiting response... 302 Found
Location: http://64.123.28.133/files/21490000000827F6/nginx.org/download/nginx-1.14.0.tar.gz [following]
--2018-08-30 06:35:21--  http://64.123.28.133/files/21490000000827F6/nginx.org/download/nginx-1.14.0.tar.gz
Connecting to 64.123.28.133:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1016272 (992K) [application/octet-stream]
Saving to: ‘nginx-1.14.0.tar.gz’

100%[================================================================================>] 1,016,272   1.76MB/s   in 0.6s

2018-08-30 06:35:22 (1.76 MB/s) - ‘nginx-1.14.0.tar.gz’ saved [1016272/1016272]

编译安装

[root@linfan src]# ls
debug  kernels  nginx-1.14.0.tar.gz
[root@linfan src]# tar xf nginx-1.14.0.tar.gz 
[root@linfan src]# ls
debug  kernels  nginx-1.14.0  nginx-1.14.0.tar.gz
[root@linfan src]# cd nginx-1.14.0
[root@linfan nginx-1.14.0]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  man  README  src
[root@linfan nginx-1.14.0]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module  --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module  --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log 
[root@linfan nginx-1.14.0]# make -j $(grep 'processor' /proc/cpuinfo | wc -l) && make install

配置环境变量

[root@linfan ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh
[root@linfan ~]# . /etc/profile.d/nginx.sh

启动nginx


[root@linfan ~]# nginx
[root@linfan ~]# ss -antl
State      Recv-Q Send-Q                Local Address:Port                               Peer Address:Port
LISTEN     0      128                               *:80                                            *:*
LISTEN     0      128                               *:22                                            *:*
LISTEN     0      100                       127.0.0.1:25                                            *:*
LISTEN     0      128                              :::22                                           :::*
LISTEN     0      100                             ::1:25                                           :::*   

验证:
在浏览器中输入服务器ip 192.168.24.148
nginx

2.访问控制

用于location段
allow:设定允许哪台或哪些主机访问,多个参数间用空格隔开
deny:设定禁止哪台或哪些主机访问,多个参数间用空格隔开、

编辑配置文件

[root@linfan ~]# vi /usr/local/nginx/conf/nginx.conf
   location / {
            root   html;
            index  index.html index.htm;
            deny 192.168.24.1;
            allow all; 

测试语法加载nginx

[root@linfan ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@linfan ~]# nginx -s reload

验证:
nginx

基于认证

创建一个存放用户认证的目录

[root@linfan nginx]# mkdir auth
[root@linfan nginx]# ll
total 4
drwxr-xr-x. 2 root  root    6 Aug 30 07:44 auth
drwx------. 2 nginx root    6 Aug 30 06:58 client_body_temp
drwxr-xr-x. 2 root  root 4096 Aug 30 07:36 conf
drwx------. 2 nginx root    6 Aug 30 06:58 fastcgi_temp
drwxr-xr-x. 2 root  root   56 Aug 30 07:21 html
drwxr-xr-x. 2 root  root   23 Aug 30 06:58 logs
drwx------. 2 nginx root    6 Aug 30 06:58 proxy_temp
drwxr-xr-x. 2 root  root   19 Aug 30 06:58 sbin
drwx------. 2 nginx root    6 Aug 30 06:58 scgi_temp
drwx------. 2 nginx root    6 Aug 30 06:58 uwsgi_temp

安装生成密码的命令

[root@linfan ~]# yum provides *bin/htpasswd
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
httpd-tools-2.4.6-80.el7.centos.x86_64 : Tools for use with the Apache HTTP Server
Repo        : base
Matched from:
Filename    : /usr/bin/htpasswd

updates/x86_64/filelists_db                                                                        | 2.9 MB  00:00:08
httpd-tools-2.4.6-80.el7.centos.1.x86_64 : Tools for use with the Apache HTTP Server
Repo        : updates
Matched from:
Filename    : /usr/bin/htpasswd

[root@linfan ~]# yum -y install httpd-tools
Loaded plugins: fastestmirror
base                                                                                               | 3.6 kB  00:00:00
centosplus                                                                                         | 3.4 kB  00:00:00
extras                                                                                             | 3.4 kB  00:00:00
updates                                                                                            | 3.4 kB  00:00:00
Loading mirror speeds from cached hostfile
Resolving Dependencies
--> Running transaction check
---> Package httpd-tools.x86_64 0:2.4.6-80.el7.centos.1 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

==========================================================================================================================
 Package                     Arch                   Version                                 Repository               Size
==========================================================================================================================
Installing:
 httpd-tools                 x86_64                 2.4.6-80.el7.centos.1                   updates                  90 k

Transaction Summary
==========================================================================================================================
Install  1 Package

Total download size: 90 k
Installed size: 169 k
Downloading packages:
httpd-tools-2.4.6-80.el7.centos.1.x86_64.rpm                                                       |  90 kB  00:00:00
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : httpd-tools-2.4.6-80.el7.centos.1.x86_64                                                               1/1
  Verifying  : httpd-tools-2.4.6-80.el7.centos.1.x86_64                                                               1/1

Installed:
  httpd-tools.x86_64 0:2.4.6-80.el7.centos.1

Complete!

创建登录nginx的用户和密码

[root@linfan ~]# htpasswd -c -m /usr/local/nginx/auth/.user_auth_file tom
New password:
Re-type new password:
Adding password for user tom

编辑配置文件


        location / {
            root   html;
            index  index.html index.htm;
            auth_basic "hello linfan"; //添加此行
            auth_basic_user_file ../auth/.user_auth_file;   //添加此行

测试语法加载nginx

[root@linfan ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@linfan ~]# nginx -s reload

验证:
nginxnginx

httpd配置

1.生成私钥
CA的配置文件:/etc/pki/tls/openssl.cnf

 [root@linfan ~]# cd /etc/pki/CA
[root@linfan CA]# (umask 077;openssl genrsa -out private/cakey.pem 2048)  #生成密钥,括号必须要
Generating RSA private key, 2048 bit long modulus
............................................................................+++
..................................................................................................................+++
e is 65537 (0x10001)
[root@linfan CA]# openssl rsa -in private/cakey.pem -pubout #提取公钥
writing RSA key
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzWfNapmbpIFvSv5ljBvg
RCkDpxoWB/yPy8uqhlmVfq5DTYRSn5iAWjZSM3xd6Fd0HLVWc2CH9kETL9QEZrTI
v5Q+pPHmcFQ4+jEG9qwnPf6xF1dngA2beIn0o7Y76yCIWeR0xy2hdJ5IjzIRzReG
2yRje8u+iZiiX1nNjGC98ABz4IG2UzDsTigfoQkQQhVJfzqP+cMbQbVL9cPFo2mT
DjvbN/NNP1GB138O2Cb1tDucgpPYzOcdiMY35BCp/XfDu+IYgpvz/gtxsRLFnBlK
ew1vZYL0mMzQrSxedm5ZKuZ21Z47l/XeiIE7J7SpAbstoJDlnPwCIrZ2mL8tyN0L
VwIDAQAB
-----END PUBLIC KEY-----

CA生成自签署证书

root@linfan CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 365 #生成自签署证书
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) []:hb
Locality Name (eg, city) [Default City]:wh
Organization Name (eg, company) [Default Company Ltd]:www.doudou.com
Organizational Unit Name (eg, section) []:www.doudou.com
Common Name (eg, your name or your server's hostname) []:www.doudou.com
Email Address []:doudou@qq.com

[root@linfan CA]# openssl x509 -text -in cacert.pem   #读出cacert.pem证书的内容
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            c6:52:14:64:e5:cb:c1:05
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=cn, ST=hb, L=wh, O=www.doudou.com, OU=www.doudou.com, CN=www.doudou.com/emailAddress=doudou@qq.com
        Validity
            Not Before: Aug 30 12:21:56 2018 GMT
            Not After : Oct  5 12:21:56 2018 GMT
        Subject: C=cn, ST=hb, L=wh, O=www.doudou.com, OU=www.doudou.com, CN=www.doudou.com/emailAddress=doudou@qq.com
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    00:cd:67:cd:6a:99:9b:a4:81:6f:4a:fe:65:8c:1b:
                    e0:44:29:03:a7:1a:16:07:fc:8f:cb:cb:aa:86:59:
                    95:7e:ae:43:4d:84:52:9f:98:80:5a:36:52:33:7c:
                    5d:e8:57:74:1c:b5:56:73:60:87:f6:41:13:2f:d4:
                    04:66:b4:c8:bf:94:3e:a4:f1:e6:70:54:38:fa:31:
                    06:f6:ac:27:3d:fe:b1:17:57:67:80:0d:9b:78:89:
                    f4:a3:b6:3b:eb:20:88:59:e4:74:c7:2d:a1:74:9e:
                    48:8f:32:11:cd:17:86:db:24:63:7b:cb:be:89:98:
                    a2:5f:59:cd:8c:60:bd:f0:00:73:e0:81:b6:53:30:
                    ec:4e:28:1f:a1:09:10:42:15:49:7f:3a:8f:f9:c3:
                    1b:41:b5:4b:f5:c3:c5:a3:69:93:0e:3b:db:37:f3:
                    4d:3f:51:81:d7:7f:0e:d8:26:f5:b4:3b:9c:82:93:
                    d8:cc:e7:1d:88:c6:37:e4:10:a9:fd:77:c3:bb:e2:
                    18:82:9b:f3:fe:0b:71:b1:12:c5:9c:19:4a:7b:0d:
                    6f:65:82:f4:98:cc:d0:ad:2c:5e:76:6e:59:2a:e6:
                    76:d5:9e:3b:97:f5:de:88:81:3b:27:b4:a9:01:bb:
                    2d:a0:90:e5:9c:fc:02:22:b6:76:98:bf:2d:c8:dd:
                    0b:57
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                72:6D:68:C7:2F:13:F1:2B:E7:0C:D2:8C:42:B2:17:A7:BC:6D:9A:92
            X509v3 Authority Key Identifier:
                keyid:72:6D:68:C7:2F:13:F1:2B:E7:0C:D2:8C:42:B2:17:A7:BC:6D:9A:92

            X509v3 Basic Constraints:
                CA:TRUE
    Signature Algorithm: sha256WithRSAEncryption
         0d:3b:df:00:69:8a:a5:80:15:a0:81:ff:57:7e:bf:60:e1:9a:
         b7:ed:7d:5a:c0:13:d1:4c:e4:38:f5:6f:a3:93:2b:df:09:f9:
         57:ee:da:15:61:ec:56:31:2e:06:fe:92:8f:7f:a3:79:2c:e7:
         77:1e:d9:23:34:79:8f:f5:c9:3f:dc:33:17:7b:74:be:da:e3:
         d0:6c:43:3d:4a:20:5b:40:e5:6b:7d:fe:e4:f7:4f:59:9d:2d:
         62:88:95:12:f7:74:66:53:9f:59:34:dd:40:44:39:56:0d:a8:
         e9:89:60:2d:ea:4c:0c:8a:49:04:56:cc:5c:8a:18:a1:9d:ea:
         52:4f:d3:ab:f0:b1:ac:29:df:9f:3c:33:4d:64:94:ea:33:70:
         b2:9b:5f:39:d8:12:27:b3:86:9f:78:3b:40:61:28:6b:49:ca:
         7d:81:f5:e4:cb:ab:db:ec:76:fc:b8:67:ce:88:13:d7:0a:a4:
         ef:d9:9f:19:b8:6c:74:a0:30:13:d9:76:47:e6:17:92:c6:04:
         51:a7:f7:6a:08:80:b1:2c:00:9b:ec:46:e2:a8:9b:1c:35:79:
         1d:7f:fe:69:0e:af:56:06:54:ff:98:c8:35:73:29:97:aa:fb:
         a3:9a:66:32:aa:a2:6b:6c:eb:e1:bb:2d:0e:68:e3:2a:31:be:
         fe:d1:fc:51
-----BEGIN CERTIFICATE-----
MIID9TCCAt2gAwIBAgIJAMZSFGTly8EFMA0GCSqGSIb3DQEBCwUAMIGQMQswCQYD
VQQGEwJjbjELMAkGA1UECAwCaGIxCzAJBgNVBAcMAndoMRcwFQYDVQQKDA53d3cu
ZG91ZG91LmNvbTEXMBUGA1UECwwOd3d3LmRvdWRvdS5jb20xFzAVBgNVBAMMDnd3
dy5kb3Vkb3UuY29tMRwwGgYJKoZIhvcNAQkBFg1kb3Vkb3VAcXEuY29tMB4XDTE4
MDgzMDEyMjE1NloXDTE4MTAwNTEyMjE1NlowgZAxCzAJBgNVBAYTAmNuMQswCQYD
VQQIDAJoYjELMAkGA1UEBwwCd2gxFzAVBgNVBAoMDnd3dy5kb3Vkb3UuY29tMRcw
FQYDVQQLDA53d3cuZG91ZG91LmNvbTEXMBUGA1UEAwwOd3d3LmRvdWRvdS5jb20x
HDAaBgkqhkiG9w0BCQEWDWRvdWRvdUBxcS5jb20wggEiMA0GCSqGSIb3DQEBAQUA
A4IBDwAwggEKAoIBAQDNZ81qmZukgW9K/mWMG+BEKQOnGhYH/I/Ly6qGWZV+rkNN
hFKfmIBaNlIzfF3oV3QctVZzYIf2QRMv1ARmtMi/lD6k8eZwVDj6MQb2rCc9/rEX
V2eADZt4ifSjtjvrIIhZ5HTHLaF0nkiPMhHNF4bbJGN7y76JmKJfWc2MYL3wAHPg
gbZTMOxOKB+hCRBCFUl/Oo/5wxtBtUv1w8WjaZMOO9s3800/UYHXfw7YJvW0O5yC
k9jM5x2IxjfkEKn9d8O74hiCm/P+C3GxEsWcGUp7DW9lgvSYzNCtLF52blkq5nbV
njuX9d6IgTsntKkBuy2gkOWc/AIitnaYvy3I3QtXAgMBAAGjUDBOMB0GA1UdDgQW
BBRybWjHLxPxK+cM0oxCshenvG2akjAfBgNVHSMEGDAWgBRybWjHLxPxK+cM0oxC
shenvG2akjAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQANO98AaYql
gBWggf9Xfr9g4Zq37X1awBPRTOQ49W+jkyvfCflX7toVYexWMS4G/pKPf6N5LOd3
HtkjNHmP9ck/3DMXe3S+2uPQbEM9SiBbQOVrff7k909ZnS1iiJUS93RmU59ZNN1A
RDlWDajpiWAt6kwMikkEVsxcihihnepST9Or8LGsKd+fPDNNZJTqM3Cym1852BIn
s4afeDtAYShrScp9gfXky6vb7Hb8uGfOiBPXCqTv2Z8ZuGx0oDAT2XZH5heSxgRR
p/dqCICxLACb7EbiqJscNXkdf/5pDq9WBlT/mMg1cymXqvujmmYyqqJrbOvhuy0O
aOMqMb7+0fxR
-----END CERTIFICATE-----

[root@linfan CA]# mkdir certs newcerts crl
[root@linfan CA]# touch index.txt && echo 01 > serial

客户端(nginx)生成密钥

[root@linfan CA]# cd /usr/local/nginx/
[root@linfan nginx]# mkdir ssl
[root@linfan nginx]# cd ssl
[root@linfan ssl]# (umask 077;openssl genrsa -out nginx.key 2048)
Generating RSA private key, 2048 bit long modulus
........+++
.+++
e is 65537 (0x10001)

客户端生成证书签署请求

[root@linfan ssl]# openssl req -new -key nginx.key -days 365 -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) []:hb
Locality Name (eg, city) [Default City]:wh
Organization Name (eg, company) [Default Company Ltd]:www.doudou.com
Organizational Unit Name (eg, section) []:www.doudou.com
Common Name (eg, your name or your server's hostname) []:www.doudou.com
Email Address []:doudou@qq.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
[root@linfan ssl]# openssl ca -in ./nginx.csr -out nginx.crt -days 365
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok 
[root@linfan ssl]# ls
nginx.crt  nginx.csr  nginx.key

编辑配置文件

[root@linfan ~]# vi /usr/local/nginx/conf/nginx.conf

...
...
  server {
        listen       443 ssl;
        server_name  www.doudou.com; //编辑此处

        ssl_certificate     /usr/local/nginx/ssl/nginx.crt;   //编辑此处

        ssl_certificate_key  /usr/local/nginx/ssl/nginx.key;  //编辑此处

        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;

        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;

        location / {
            root   html;
            index  index.html index.htm;
        }
    }

}                                     

测试语法以及加载nginx

[root@linfan ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@linfan ~]#  nginx -s reload

在本机加入ip与网站的映射关系
nginx

验证:
nginxnginx

开启状态界面

编辑配置文件

/修改成如下内容:
  location /status {
           stub_status on;
           allow 192.168.24.1;
           deny  all;
        }      

测试语法以及加载nginx

[root@linfan ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@linfan ~]#  nginx -s reload

验证:
nginx

[root@linfan html]# mkdir images
[root@linfan html]# ll
total 12
-rw-r--r--. 1 root root 537 Aug 30 20:54 50x.html
drwxr-xr-x. 2 root root   6 Aug 30 22:20 images
-rw-r--r--. 1 root root 612 Aug 30 20:54 index.html
-rw-r--r--. 1 root root  24 Aug 30 21:14 test.php
[root@linfan html]# cd images
//在此上传一张图片
[root@linfan images]# ls
a.png

编辑文件

//添加以下内容
         location /images {
            root   html;
            index  index.html;
        }         

测试语法以及加载nginx

[root@linfan ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@linfan ~]#  nginx -s reload

验证:
nginx

重名名images目录为doudou

[root@linfan html]# mv images doudou
[root@linfan html]# cd doudou
[root@linfan doudou]# ls
a.png

编辑配置文件


         location /images {
            root   html;
            index  index.html;
            rewrite ^/images/(.*\.jpg)$ /doudou/$1 break;   

测试语法以及加载nginx

[root@linfan ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@linfan ~]#  nginx -s reload

验证:
nginx

映射网页验证

映射到www.qq.com

编辑配置文件

//修改成如下内容:
 location /doudou {
            root   html;
            index  index.html;
            rewrite ^/doudou/(.*)$ http://www.qq.com/index.html redirect;
        }       

测试语法以及加载nginx

[root@linfan ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@linfan ~]#  nginx -s reload

验证:
nginxnginx

if

语法:if (condition) {...}

应用场景:

server段
location段

常见的condition

  • 变量名(变量值为空串,或者以“0”开始,则为false,其他的均为true)

  • 以变量为操作构成的比较表述式(可使用=,!=类似的比较操作符)

  • 正则表达式的模式匹配操作
    • ~:区分大小写的模式匹配检查
    • ~*:不区分大小写的模式匹配检查
    • !~ 和!~*:对上面两种测试取反
  • 测试指定路径为文件的可能性(-f,!-f)
  • 测试指定路径为目录的可能性(-d,!-d)
  • 测试文件的存在性(-e,!e)
  • 检查文件是否有执行权限(-x,!x)

    基于浏览器实现分离案例

除了谷歌浏览器以外都不可以访问

编辑配置文件:

[root@linfan ~]# vim /usr/local/nginx/conf/nginx.conf 
...
...
        location / {
            root   html;
            index  index.html index.htm;
        }
        //添加以下内容
        location /images {
           if ($http_user_agent ~ Chrome) {
               rewrite ^/images/(.*)$ /chrome/doudou/$1 break;
            }
         }                                        
...
...

创建在网站存放根目录下面创建/chrome以及chrome/doudou/目录并在chrome/doudou/上传一张图片

root@linfan html]# mkdir -p chrome/doudou/
[root@linfan html]# ls
50x.html  chrome  index.html
[root@linfan html]# cd chrome/
[root@linfan chrome]# ls
doudou
[root@linfan chrome]# cd doudou/
[root@linfan doudou]# ls
1.png

验证:
在谷歌浏览器上输入http://192.168.24.148/images/1.png
nginx
可以正常访问

在其他浏览器上输入http://192.168.24.148/images/1.png
nginx
无法访问

防盗链案例

 location ~* \.(jpg|gif|jpeg|png)$ {
    valid_referer none clocked www.idfsoft.com;
    if ($invalid_referer) {
      rewrite ^/ http://www.idfsoft.com/403.html;
    }
}

反向代理与负载均衡

nginx通常被用作后端服务器的反向代理,这样就可以很方便的实现动静分离以及负载均很,从而大大提高服务器的处理能力。
在upstream段内,定义一个服务器列表,默认的方式是轮询,如果要确定同一访问者发出的请求总是由同一个后端服务器来处理,可以设置ip_hash

开启另外的二台服务器
IP地址为 192,168.24.131
和192.168.24.146 并在服务器里面配置httpd

[root@linfan ~]# setenforce 0
setenforce: SELinux is disabled
[root@linfan ~]# sed -ri 's/^(SELINUX=).*/\1disabled/g' /etc/selinux/config
[root@linfan ~]# systemctl stop firewalld
[root@linfan ~]# systemctl disable firewalld
[root@linfan ~]# cd /etc/yum.repos.d/
[root@linfan yum.repos.d]# ls
163.repo
[root@linfan yum.repos.d]# cd
[root@linfan ~]# yum -y install httpd
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
Resolving Dependencies
--> Running transaction check
---> Package httpd.x86_64 0:2.4.6-80.el7.centos.1 will be installed
--> Processing Dependency: httpd-tools = 2.4.6-80.el7.centos.1 for package: httpd-2.4.6-80.el7.centos.1.x86_64
--> Processing Dependency: /etc/mime.types for package: httpd-2.4.6-80.el7.centos.1.x86_64
--> Running transaction check
---> Package httpd-tools.x86_64 0:2.4.6-80.el7.centos.1 will be installed
---> Package mailcap.noarch 0:2.1.41-2.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

==========================================================================================================================
 Package                     Arch                   Version                                 Repository               Size
==========================================================================================================================
Installing:
 httpd                       x86_64                 2.4.6-80.el7.centos.1                   updates                 2.7 M
Installing for dependencies:
 httpd-tools                 x86_64                 2.4.6-80.el7.centos.1                   updates                  90 k
 mailcap                     noarch                 2.1.41-2.el7                            base                     31 k

Transaction Summary
==========================================================================================================================
Install  1 Package (+2 Dependent packages)

Total download size: 2.8 M
Installed size: 9.6 M
Downloading packages:
(1/3): mailcap-2.1.41-2.el7.noarch.rpm                                                             |  31 kB  00:00:00
(2/3): httpd-tools-2.4.6-80.el7.centos.1.x86_64.rpm                                                |  90 kB  00:00:01
(3/3): httpd-2.4.6-80.el7.centos.1.x86_64.rpm                                                      | 2.7 MB  00:00:15
--------------------------------------------------------------------------------------------------------------------------
Total                                                                                     182 kB/s | 2.8 MB  00:00:15
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : httpd-tools-2.4.6-80.el7.centos.1.x86_64                                                               1/3
  Installing : mailcap-2.1.41-2.el7.noarch                                                                            2/3
  Installing : httpd-2.4.6-80.el7.centos.1.x86_64                                                                     3/3
  Verifying  : mailcap-2.1.41-2.el7.noarch                                                                            1/3
  Verifying  : httpd-tools-2.4.6-80.el7.centos.1.x86_64                                                               2/3
  Verifying  : httpd-2.4.6-80.el7.centos.1.x86_64                                                                     3/3

Installed:
  httpd.x86_64 0:2.4.6-80.el7.centos.1

Dependency Installed:
  httpd-tools.x86_64 0:2.4.6-80.el7.centos.1                         mailcap.noarch 0:2.1.41-2.el7

Complete!
[root@linfan ~]# cd /var/www/html
[root@linfan html]# ls
[root@linfan html]# echo "hello mary" >> index.html  //另外一台输入不同的内容以便区分
[root@linfan html]# systemctl start httpd
ss[root@linfan html]#
[root@linfan html]# ss -natl
State      Recv-Q Send-Q                Local Address:Port                               Peer Address:Port
LISTEN     0      128                               *:22                                            *:*
LISTEN     0      100                       127.0.0.1:25                                            *:*
LISTEN     0      128                              :::80                                           :::*
LISTEN     0      128                              :::22                                           :::*
LISTEN     0      100                             ::1:25                                           :::* 

在分别输入这台服务器的IP地址:
nginx
nginx

在最初的服务器上配置负载均衡

编辑配置文件


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;
    //http下加入以下内容
    upstream web {
       server 192.168.24.131;
       server 192.168.24.146;  
          }
        server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;
//在此处输入以下内容
        location / {
            proxy_pass http://web;
        }

替换掉

 location / {
            root   html;
            index  index.html index.htm;
        }

输入负载均衡服务器的ip地址验证

nginxnginx
不断刷新 发现不断轮询