1. 程式人生 > >nginx一些常用的配置操作

nginx一些常用的配置操作

訪問控制

①.在location段設定

`[[email protected] ~]# vim /usr/local/nginx/conf/nginx.conf
 allow 172.16.11.14/32;        //允許172.16.11.14訪問
 deny 172.16.11.15/32;        //拒絕172.16.11.15訪問

測試
在172.16.11.14上訪問

[[email protected] ~]# curl 172.16.11.13
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

在172.16.11.15上訪問

[[email protected] ~]# curl 172.16.11.13
<html>
<head><title>403 Forbidden</title></head>
<body bgcolor="white">
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.14.0</center>
</body>
</html>

基於使用者認證

①.安裝htpasswd命令,然後生成使用者和密碼

[[email protected] ~]# yum -y install httpd-tools
[[email protected] ~]# touch /usr/local/nginx/pass
[[email protected] ~]# htpasswd -c -m /usr/local/nginx/pass lzh     //為使用者lzh生成密碼,這裡使用者不是系統使用者
New password: 
Re-type new password: 
Adding password for user lzh
[
[email protected]
~]# cat /usr/local/nginx/pass lzh:$apr1$4o0wpgvQ$N97Tt5oRWkHJwmJRj3X8E0

②.修改配置檔案

[[email protected] ~]# vim /usr/local/nginx/conf/nginx.conf
auth_basic "haha";            //歡迎資訊
auth_basic_user_file "/usr/local/nginx/pass";           //放使用者密碼的檔案
[[email protected] ~]# nginx -s reload

測試
在這裡插入圖片描述

在這裡插入圖片描述

配置證書

  • 172.16.11.15(CA)
    ①.生成一對金鑰
[[email protected] ~]# cd /etc/pki/CA/
[[email protected] CA]# (umask 077;openssl genrsa -out private/cakey.pem 2048)               //生成金鑰
Generating RSA private key, 2048 bit long modulus
.........................................................+++
....................................+++
e is 65537 (0x10001)
[[email protected] CA]# openssl rsa -in private/cakey.pem -pubout         //提取公鑰
writing RSA key
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtsrXOuQXSQSv0UTTFycm
1SC9Fs6whSEXkKLdmVr6VLrpfqPky/X4B4TjbXFNrG5GFeVMfSztvuNpJH89PIsO
XHMAIODBDqt6IiVqynClWD0kzR+w+e9HjFz0LO9r0aS+jui2nrssKcRm0p84Fm9K
h062bujEvYqkRWdIwBCJ5zv7bN5D+KNcnc9I3oOfbMTIqz1tCe7LrWoE2yJsAeH7
my0OVU4rjxRLCnmuvXOO0jwBUT0x4B+fmsvx0i2pjxJhNlxHgx8niTTEpIKtPij6
mVdPWUO2aVvtmljgPbhpsRweAfiLVmHOxYPL6Q1l6b7rsgQ/HDPB7eKCZXGh0gb+
lQIDAQAB
-----END PUBLIC KEY-----

②.生成自簽署證書

`[[email protected] CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 7     //生成7天的自簽署證書
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.abc.com        //這裡寫公司域名
Organizational Unit Name (eg, section) []:www.abc.com         //同上
Common Name (eg, your name or your server's hostname) []:www.abc.com          //顯示的名稱
Email Address []:[email protected]           //郵箱地址
[[email protected] CA]# openssl x509 -text -in cacert.pem              //讀出公鑰的內容
[[email protected] CA]# touch index.txt && echo 01 > serial
  • 172.16.11.13(客戶端,也就是nginx的伺服器)
    ①.生成金鑰
[[email protected] ~]# cd /usr/local/nginx/
[[email protected] nginx]# mkdir ssl
[[email protected] nginx]# cd ssl
[[email protected] ssl]# (umask 077;openssl genrsa -out nginx.key 2048)     //生成金鑰
Generating RSA private key, 2048 bit long modulus
.................+++
..................................................................................................+++
e is 65537 (0x10001)

②.生成證書籤署請求

[[email protected] ssl]# openssl req -new -key nginx.key -days 7 -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.abc.com         //公司域名
Organizational Unit Name (eg, section) []:www.abc.com       //同上
Common Name (eg, your name or your server's hostname) []:nginx             //伺服器名稱
Email Address []:[email protected]        //郵箱地址

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:1234        //密碼
An optional company name []:nginx         //名稱

③.客戶端把證書籤署請求檔案傳送給CA

[[email protected] ssl]# scp nginx.csr [email protected]:/root
[email protected]'s password: 
nginx.csr                                           100% 1090   845.0KB/s   00:00 
  • 172.16.11.15

①.簽署客戶端提交上來的證書

[[email protected] CA]# openssl ca -in /root/nginx.csr -out nginx.crt -days 7
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: Oct 24 18:42:31 2018 GMT
            Not After : Oct 31 18:42:31 2018 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = HB
            organizationName          = www.abc.com
            organizationalUnitName    = www.abc.com
            commonName                = nginx
            emailAddress              = [email protected]
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                F7:E6:13:08:0B:A8:F7:AD:8A:7B:E2:9E:CF:47:80:1A:DA:5D:37:C5
            X509v3 Authority Key Identifier: 
                keyid:E5:01:00:BB:3A:12:6C:1D:69:2B:4A:4C:9C:B0:DD:0F:3F:B9:81:E1

Certificate is to be certified until Oct 31 18:42:31 2018 GMT (7 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

②.把簽署好的證書發給客戶端

[[email protected] CA]# scp nginx.crt [email protected]:/usr/local/nginx/ssl/
[email protected]'s password: 
nginx.crt                                           100% 4565     3.0MB/s   00:00 
  • 172.16.11.13
    修改配置檔案
[[email protected] ssl]# vim /usr/local/nginx/conf/nginx.conf
    server {
        listen       443 ssl;
        server_name  www.abc.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;
    }
    }
    [[email protected] ssl]# nginx -s reload

在這裡插入圖片描述

開啟狀態頁面

配置檔案

[[email protected] ssl]# vim /usr/local/nginx/conf/nginx.conf
        location /status {
            stub_status on;
            allow 192.168.0.0/16;
            deny all;

        }
[[email protected] ssl]# nginx -s reload

測試
在這裡插入圖片描述

rewrite

[[email protected] ~]# vim /usr/local/nginx/conf/nginx.conf
        location /abc {
            root   /opt;
            index index.html;
            rewrite ^/abc/(.*\.html) /aaa/$1 last;        //將/abc的url重寫成/aaa的,並接上last往下面繼續匹配
        }
        location /aaa {
            root /opt;
            index index.html;
            rewrite ^/aaa/(.*\.html) /ccc/$1 break;           //將/aaa的url重寫成/ccc的,並停止匹配

        }
[[email protected] ~]# mkdir /opt/{abc,aaa,ccc}
[[email protected] ~]# echo 'xx' > /opt/abc/a.html && echo 'xxx' > /opt/aaa/a.html && echo 'xxxx' > /opt/ccc/a.html 

使用/abc的url最終匹配出來的是/ccc的
在這裡插入圖片描述

基於瀏覽器實現分離

①.修改配置檔案

[[email protected] ~]# vim /usr/local/nginx/conf/nginx.conf
        location / {
            root html;
           index index.html;
            if ($http_user_agent ~ Firefox){
               rewrite ^(.*)$ /firefox/$1 break;
            }
            if ($http_user_agent ~ Chrome) {
               rewrite ^(.*)$ /chrome/$1 break;
            }
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

②.建立不同的訪問網頁檔案

[[email protected] ~]# mkdir /usr/local/nginx/html/firefox
[[email protected] ~]# mkdir /usr/local/nginx/html/chrome
[[email protected] ~]# echo 'firefox' > /usr/local/nginx/html/firefox/index.html
[[email protected] ~]# echo 'chrome' > /usr/local/nginx/html/chrome/index.html

測試
在谷歌上訪問
在這裡插入圖片描述

在火狐上訪問
在這裡插入圖片描述

反向代理與負載均衡

伺服器型別 ip 安裝的服務
代理伺服器 172.16.11.13 nginx
目標伺服器 172.16.11.14 nginx
目標伺服器 172.16.11.15 httpd
  • 172.16.11.14

使用yum安裝nginx並啟動服務

[[email protected] ~]# yum -y install epel-release
[[email protected] ~]# yum -y install nginx
[[email protected] ~]# systemctl start nginx.service 
[[email protected] ~]# 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            :::80                         :::*                  
LISTEN     0      128            :::22                         :::*                  
LISTEN     0      100           ::1:25                         :::*    
  • 172.16.11.15

①.使用yum安裝httpd

[[email protected] ~]# yum -y install epel-release
[[email protected] ~]# yum -y install httpd

②.配置httpd網頁檔案並啟動服務

[[email protected] ~]# echo 'http hello' > /var/www/html/index.html 
[[email protected] ~]# systemctl start httpd
[[email protected] ~]# ss -antl
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                         :::*     
  • 172.16.11.13

修改配置檔案

[[email protected] ~]# vim /usr/local/nginx/conf/nginx.conf
upstream xx.com {                               //負載均衡配置在httpd段
    server 172.16.11.14:80 weight=1;
    server 172.16.11.15:80 weight=2;
}
        location / {
            root html;
            proxy_pass http://xx.com;                 //反向代理
            index index.html;
}

測試
在這裡插入圖片描述

在這裡插入圖片描述