1. 程式人生 > 實用技巧 >01-Nginx基礎知識

01-Nginx基礎知識

一、什麼是Nginx

# nginx 是一個 web伺服器 ( 靜態資源 )  代理伺服器...

二、Nginx應用場景

"""
1.web伺服器
2.反向代理 代理服務 ( PHP Python Golang Java )
    2.1) 負載均衡
    2.2) 快取
        3.安全服務https
"""

三、Nginx組成結構

"""
二進位制檔案:         Nginx主體框架能實現基本的請求與響應功能( 原始碼 + 模組 = 編譯 )汽車的基本框架,提供駕駛功能
nginx配置檔案:      控制Nginx的行為,能做什麼不能做什麼,控制汽車前往的目的地
access_log日誌:    記錄每一條使用者的http 請求,GPS記錄行動軌跡
error_log日誌:     服務無法執行,或出現異常時,可以通過error_log定位故障,黑匣子,分析故障,和定位故障
"""

1、配置官方yum源

epel源獲取,使用過程中就會出現許可權不足的問題

2、執行命令安裝

[root@kkk-pythonedu ~]# wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
[root@kkk-pythonedu ~]# yum install nginx -y
[root@kkk-pythonedu ~]# rpm -q nginx
nginx-1.16.1-1.el7.x86_64

3、安裝後的目錄結構

[root@kkk-pythonedu ~]# rpm -ql nginx
/etc/logrotate.d/nginx # 日誌輪轉 ( 日誌切割 ) /etc/nginx/ # nginx配置檔案目錄 /etc/nginx/nginx.conf # nginx主配置檔案 /var/log/nginx # 日誌目錄

4、Nginx配置檔案

[root@kkk-pythonedu ~]# systemctl stop httpd
[root@kkk-pythonedu ~]# systemctl disable httpd
[root@kkk-pythonedu ~]#
systemctl start nginx [root@kkk-pythonedu ~]# netstat -lntp | grep 80 tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 26551/nginx: master

cat /etc/nginx/nginx.conf

user nginx;                                         # 執行nginx的使用者身份
worker_processes auto;                              # worker程序執行多少個, auto自動與cpu核心保持一致
error_log /var/log/nginx/error.log;                 # 錯誤日誌
pid /run/nginx.pid;                                 # 程序執行後,在該目錄下存放一個pid檔案,檔案中記錄的是該程序的ID編號

include /usr/share/nginx/modules/*.conf;            # 包含所有的模組配置檔案

events {
    worker_connections 1024;                        # worker的最大連線數   [  worker_connections *  worker_processes ]
}

    
http {            # 負責http的請求與響應
    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  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;            # 存放的都是nginx能支援的檔案型別
    default_type        application/octet-stream;        # 當 nginx 不支援該型別時,預設以下載的方式回傳給使用者

    include /etc/nginx/conf.d/*.conf;                    # 包含conf.d/*.conf結尾的檔案    [ 定義的一個又一個的網站 ]
}

第一步: 關閉防火牆  

  firewalld
    systemctl stop firewalld
    systemctl disable firewalld
  selinux
    setenforce 0
    sed -i 's#SELINUX=enforcing#SELINUX=disabled#g' /etc/selinux/config

清除nginx.conf中所有的註釋,以及server整個段的內容

第二步:新建一個站點

# [root@kkk-pythonedu ~]# cat /etc/nginx/conf.d/test.kkk.com.conf
server {
    listen 80;
    server_name test.kkk.com;

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

根據配置檔案定義的路徑,建立該路徑,並放入程式碼

[root@kkk-pythonedu ~]# mkdir /code/html -p 
[root@kkk-pythonedu ~]# echo "test-kkk.com....." > /code/html/index.html

檢查配置檔案是否有錯誤的地方

[root@kkk-pythonedu ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

過載服務,並生效

[root@kkk-pythonedu ~]# systemctl restart nginx    

配置Hosts解析 ( 假的域名 )

Windows:  C:\Windows\System32\drivers\etc
            10.0.0.201 test.kkkedu.com

MacOS:    /etc/hosts
            10.0.0.201 test.kkk.com

5、伺服器在新增一個遊戲的站點

nginx.conf 主配置檔案一般不動

[root@kkk-pythonedu ~]# cat /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    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  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    include /etc/nginx/conf.d/*.conf;
}

第一步、編輯nginx配置檔案

[root@kkk-pythonedu ~]# cat /etc/nginx/conf.d/game.kkkedu.com.conf

 server {
   listen 80; # 監聽的埠
   server_name game.kkkedu.com; # 申明域名

   location / { # 匹配使用者請求的uri路徑
   root /code/html; # 告訴 nginx 站點的程式碼在哪裡目錄下
   index index.html index.htm; # 定義 預設返回的主頁面
 }

第二步、根據配置,建立目錄,上傳程式碼

[root@kkk-pythonedu ~]# mkdir /code/game -p
[root@kkk-pythonedu ~]# cd /code/game/
[root@kkk-pythonedu game]# rz
[root@kkk-pythonedu game]# unzip html5_\(1\).zip 

第三步、檢查nginx配置檔案語法,然後過載服務

[root@kkk-pythonedu game]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@kkk-pythonedu game]# systemctl restart nginx

第四步、配置Hosts解析(假的)

Windows電腦沒有Hosts檔案,  新建出來.

Windows:  C:\Windows\System32\drivers\etc
                10.0.0.200 test.kkkedu.com
                10.0.0.200 game.kkkedu.com

5、Nginx整個流程

"""
1.使用者通過瀏覽器請求game.kkkedu.com   
2.瀏覽器會新增一些協議頭資訊,攜帶上預設的請求uri,  http://game.kkkedu.com/
3.瀏覽器會發起DNS解析,解析game.kkkedu.com  對應的真實IP地址   
4.瀏覽器獲取到真實的IP地址後,  通過  IP+Prot的方式請求應用程式Nginx
5.Nginx接受到請求後,會進行事件的處理, 將使用者請求的 Request 資訊中 包含的 Host 欄位, 與 Server_name 欄位進行匹配
    5.1) 如果匹配不成功,則會隨機返回一個站點的頁面給使用者.
    5.2) 可以通過 在 listen 80 default_server; 方式來定義具體預設返回哪個站點給使用者.
    5.3) 如果碰到非法的域名,可以拒絕,也可以做跳轉.
            拒絕:
                return 500;
            跳轉:
                return 302 https://www.jd.com;
6.如果匹配成功, 接下來進行location uri地址匹配, 獲取要返回的檔案所在的路徑 + 預設返回的頁面 
7.Nginx獲取磁碟上的檔案, 然後構建響應報文,回傳給瀏覽器,瀏覽器載入並且渲染最終的結果呈現給使用者.
"""

四、Nginx基礎模組

1、目錄索引 auto_index

能實現和阿里雲mirrors.aliyun.com 一樣的效果.

[root@kkk-pythonedu ~]# cat /etc/nginx/conf.d/mirror.kkkedu.com.conf
server {
    listen 80;
    server_name mirror.kkkedu.com;
    charset utf8;

    location / {
        root /code/mirror;
        autoindex on;                    # 開啟目錄索引功能
        autoindex_exact_size off;        # 顯示檔案具體大小
        autoindex_localtime on;          # 顯示本地伺服器時間 
    }
}
[root@kkk-pythonedu ~]# nginx -t
[root@kkk-pythonedu ~]# systemctl restart nginx

[root@kkk-pythonedu ~]# mkdir -p /code/mirror
[root@kkk-pythonedu ~]# cd /code/mirror 
[root@kkk-pythonedu ~]# rz

1.1、訪問限制

給予來源IP限制

"""
1) 僅允許 10.0.0.1 訪問,其他訪問全部拒絕

server {
    ...
    allow 10.0.0.1/32;
    deny all;
    ...
}

2) 拒絕10.0.0.1 訪問, 其他全部允許

server {
    ...
    deny 10.0.0.1/32;
    allow all;
    ...
}
"""

測試的curl命令:
[root@kkk-pythonedu mirror]# curl -HHost:mirror.kkkedu.com http://10.0.0.200/

1.2、基於使用者與密碼 auth_basic_module

[root@kkk-pythonedu ~]# yum install httpd-tools -y
[root@kkk-pythonedu nginx]# htpasswd -c -b password_file kkk 123
[root@kkk-pythonedu nginx]# cat password_file 
kkk:$apr1$7dYbXvco$LSJaBM3HqlK3k1kkRt2Ya.

nginx配置檔案:

server {
    listen 80;
    server_name mirror.kkkedu.com;
    charset utf8;

    auth_basic "hello,nginx";                # 描述資訊
    auth_basic_user_file password_file;        # 定義密碼檔名稱

    location / {
        root /code/mirror;
        autoindex on;
        autoindex_exact_size off;
        autoindex_localtime on;
    }
}

1.3、登入後work需要密碼 、public無需密碼

[root@kkk-pythonedu ~]# mkdir /basic/{work,public} -p
[root@kkk-pythonedu mirror]# cat /etc/nginx/conf.d/basic.kkkedu.com.conf 
server {
    listen 80;
    server_name basic.kkkedu.com;
    root /basic;
    autoindex on;

    location / {
    }

    location /work {
        auth_basic "test_work";
        auth_basic_user_file password_file;
    }
}
[root@kkk-pythonedu mirror]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@kkk-pythonedu mirror]# systemctl restart nginx

點選public

點選work

1.4、限制連結 limit_conn

場景: 下載

[root@kkk-pythonedu mirror]# cat  /etc/nginx/conf.d/mirror.kkkedu.com.conf 
limit_conn_zone $binary_remote_addr zone=addr:10m;            # 定義限制的key, 分配區域大小
server {
    listen 80;
    server_name mirror.kkkedu.com;
    charset utf8;
    limit_conn addr 1;            # 呼叫區域限制,限制key只可以出現1次, 相當於限制來源客戶端IP的連線數為1
    limit_conn_status 500;        # 限制成功後,會返回500的錯誤狀態碼,預設返回503
    
    limit_rate_after 200m;        # 全速下載200m資源
    limit_rate       300k;        # 達到200m以後,限制300k的速度

    error_page 500 = @testerror;    # 如果 出現500錯誤,則讓其跳轉到內部的 @testerror 
    
    location @testerror {            # 定義 @testerror, 返回具體的動作 
        default_type text/html;
        return 200 '$remote_addr 你超過了最大連線限制, 請充值VIP解封!';
    }
    location / {
        root /code/mirror;
        autoindex on;
        autoindex_exact_size off;
        autoindex_localtime on;
    }
}

1.5、狀態監控 stub_status

location = /status {
    stub_status;
}
"""
Active connections: 2                 
server accepts handled requests
 74 74 104 
Reading: 0 Writing: 1 Waiting: 1 


Active connections: # 活躍的連線數
accepts:             # 接受的總TCP連線數
handled:             # 總處理的TCP連線數
requests:             # 總的 http 請求數
"""