前端需要掌握的Nginx知識點

什么是Nginx?


Nginx是一款免費開源的高性能HTTP服務(wù)器以及反向代理服務(wù)器(Reverse Proxy),同時可以提供IMAP/POP3/SMATP代理服務(wù)等功能。能夠快速的響應(yīng)靜態(tài)頁面請求和支持第三方功能模塊擴(kuò)展。

下載 (2).png

Nginx的優(yōu)點


  • 高并發(fā)、高性能(官方給出的并發(fā)數(shù)據(jù)5萬,實際中可以達(dá)到2-4萬)
  • 輕量級、內(nèi)存消耗少
  • 穩(wěn)定性高,宕機(jī)概率低
  • 支持熱部署
  • 模塊化設(shè)計,擴(kuò)展性較好
  • cpu親和

Nginx常用的場景


  • 靜態(tài)資源服務(wù)器
  • 動態(tài)匹配
  • 反向代理
  • Gzip壓縮
  • 負(fù)載均衡

Nginx的安裝配置


mac下鏡像飛速安裝Homebrew教程: https://zhuanlan.zhihu.com/p/90508170

$ brew install nginx

Nginx常用的命令


  • 啟動: nginx
  • 查看版本號: nginx -v
  • 查看nginx 編譯的參數(shù): nginx -V
  • 重新啟動nginx: nginx -s reload
  • 優(yōu)雅重啟,并重新載入配置文件nginx.conf: /usr/local/nginx/sbin/nginx -s reload
  • 優(yōu)雅停止nginx,有連接時會等連接請求完成再殺死worker進(jìn)程 /usr/local/nginx/sbin/nginx -s quit
    具體常用的命令參考如下:
nginx -s stop       快速關(guān)閉Nginx,可能不保存相關(guān)信息,并迅速終止web服務(wù)。
nginx -s quit       平穩(wěn)關(guān)閉Nginx,保存相關(guān)信息,有安排的結(jié)束web服務(wù)。
nginx -s reload     因改變了Nginx相關(guān)配置,需要重新加載配置而重載。
nginx -s reopen     重新打開日志文件。
nginx -c filename   為 Nginx 指定一個配置文件,來代替缺省的。
nginx -t            不運行,僅測試配置文件。nginx 將檢查配置文件的語法的正確性,并嘗試打開配置文件中所引用到的文件。
nginx -v            顯示 nginx 的版本。
nginx -V            顯示 nginx 的版本,編譯器版本和配置參數(shù)。

成功看到歡迎頁面~!(對應(yīng)的html是/usr/local/var/www/index.html)


截屏2021-05-31 下午3.14.28.png

Nginx的默認(rèn)配置


Nginx 安裝目錄下的nginx.conf就是Nginx全局的配置文件,我們主要修改這里的內(nèi)容。nginx.conf.default作為配置文件的備份。

nginx默認(rèn)使用8080端口 如果發(fā)現(xiàn)端口被占用了,可以殺掉使用使用改端口的進(jìn)程,也可以修改/usr/local/etc/nginx/nginx.conf下的

http {
    server {
        listen       8181;
        server_name  localhost;  

        #charset koi8-r;
        .....
        }
    }

其中nginx.conf中的配置信息如下:


#user  nobody;
#設(shè)置工作進(jìn)程的數(shù)量
worker_processes  1;

#錯誤日志存放目錄
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#進(jìn)程pid存放位置
#pid        logs/nginx.pid;

# 處理連接
events {
    # 設(shè)置連接數(shù),單個后臺進(jìn)程的最大并發(fā)數(shù)
    worker_connections  1024;
}


http {
    # 文件拓展名查找集合
    include       mime.types;
    # 當(dāng)查找不到對應(yīng)類型的時候默認(rèn)值
    default_type  application/octet-stream;

    # 日志格式,定義別名為 main
    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';
    
    #nginx訪問日志存放位置
    #access_log  logs/access.log  main;

    # 調(diào)用 sendfile 系統(tǒng)傳輸文件
    sendfile        on;  #開啟高效傳輸模式
    #tcp_nopush     on; #減少網(wǎng)絡(luò)報文段的數(shù)量

    # 客戶端與服務(wù)器連接超時時間,超時自動斷開
    #keepalive_timeout  0;
    keepalive_timeout  65;

    # 開啟gizip 壓縮
    #gzip  on;

    # 虛擬主機(jī)
    server {
        listen       8181;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        # 路由
        location / {
            root   html;
            index  index.html index.htm;

            #第一種情況 拒絕訪問ip地址段為 50-100 的ip訪問
            deny 192.168.10.50/100;
            
            # 第二種情況 只允許ip地址為 192.168.10.50 的ip訪問
            allow 192.168.10.50;
            deny all;
            
            # 第三種情況 這樣配置都不能訪問,從上到下依次匹配
            deny all;
            allow 192.168.10.50;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

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


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.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;
    #    }
    #}
    include servers/*;
}

搭建靜態(tài)站點

# 虛擬主機(jī)server塊
server {
    # 端口
    listen   8080;
    # 匹配請求中的host值
    server_name  localhost;
    
    # 監(jiān)聽請求路徑
    location / {
        # 查找目錄
        root /source;
        # 默認(rèn)查找
        index index.html index.htm;
    }
}

字段說明:

  • server 配置虛擬主機(jī)的相關(guān)參數(shù),可以有多個
  • server_name 通過請求中的host值 找到對應(yīng)的虛擬主機(jī)的配置
  • location 配置請求路由,處理相關(guān)頁面情況
  • root 查找資源的路徑

配置完成后執(zhí)行 nginx -t 看是否有錯誤,如果看到的是下面這種就是成功了

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

然后執(zhí)行nginx -s reload 更新Nginx配置文件,這時候打開瀏覽器 輸入 localhost:8080 應(yīng)該就能看到你的頁面了。

動態(tài)匹配(請求過濾)

通常在開發(fā)環(huán)境或者測試環(huán)境的時候呢我們修改了代碼,因為瀏覽器緩存,可能不會生效,需要手動清除緩存,才能看到修改后的效果,這里我們做一個配置讓瀏覽器不緩存相關(guān)的資源。

location ~* \.(js|css|png|jpg|gif)$ {
    add_header Cache-Control no-store;
}

~* .(js|css|png|jpg|gif)$ 是匹配以相關(guān)文件類型然后單獨處理。 add_header 是給請求的響應(yīng)加上一個頭信息Cache-Control no-store,告知瀏覽器禁用緩存,每次都從服務(wù)器獲取 效果如下:

截屏2021-05-31 下午3.37.13.png

匹配規(guī)則

location = / {
    [ configuration A ]
}

location / {
    [ configuration B ]
}

location /documents/ {
    [ configuration C ]
}

location ^~ /images/ {
    [ configuration D ]
}

location ~* \.(gif|jpg|jpeg)$ {
    [ configuration E ]
}

location =|~|~*|^~| /uri/

  • = 表示精確匹配。只有請求的url路徑與后面的字符串完全相等時,才會命中(優(yōu)先級最高)。
  • ^~ 表示如果該符號后面的字符是最佳匹配,采用該規(guī)則,不再進(jìn)行后續(xù)的查找。
  • ~ 表示該規(guī)則是使用正則定義的,區(qū)分大小寫。
  • ~* 表示該規(guī)則是使用正則定義的,不區(qū)分大小寫。
  • / 通用匹配,任何請求都會匹配到

通過狀態(tài)碼來過濾請求

# 通過狀態(tài)碼,返回指定的錯誤頁面
error_page 500 502 503 504 /50x.html;
location = /50x.html {
    root /source/error_page;
}

反向代理解決跨域


在前后端分離的開發(fā)中,跨域問題是一個非常常見的問題,現(xiàn)在解決跨域問題比較常用的兩種方式為:

  • 跨域資源請求(CORS)
  • Nginx反向代理


    612653-20190226142303336-49757621.png
截屏2021-05-31 下午4.29.29.png

先來看上面的圖 ,當(dāng)用戶請求xx.720ui.com/server1的時候,Nginx會將請求轉(zhuǎn)發(fā)給Server1這個服務(wù)器上的具體應(yīng)用,從而達(dá)到跨域的目的

同時nginx解決跨域時常用的參數(shù)配置。

location /api {   
    # 請求host傳給后端
    proxy_set_header Host $http_host;
    # 請求ip 傳給后端
    proxy_set_header X-Real-IP $remote_addr;
    # 請求協(xié)議傳給后端
    proxy_set_header X-Scheme $scheme;
    # 路徑重寫
    rewrite  /api/(.*)  /$1  break;
    # 代理服務(wù)器
    proxy_pass http://localhost:9000;
}
  • 攔截路徑/api, 可以通過正則匹配
  • proxy_set_header 允許重新定義或添加字段傳遞給代理服務(wù)器的請求頭
  • $http_host remote_addr、scheme 為Nginx內(nèi)置變量
  • rewrite 根據(jù)rewrite后的請求URI,將路徑重寫,如:接口路徑為 /user, 我們可以請求 /api/user。(為什么需要重寫uri?因為在使用Nginx做反向代理的時候,需要匹配到跨域的接口再做轉(zhuǎn)發(fā),為了方便匹配,會人為的在原接口中添加一段路徑(或標(biāo)示, 如例子中的api),因此需要在匹配之后、轉(zhuǎn)發(fā)之前把添加的那段去掉,因此需要rewrite)
  • break 繼續(xù)本次請求后面的處理 ,停止匹配下面的location。需要注意的是與之類似的last執(zhí)行過程則是停止當(dāng)前這個請求,并根據(jù)rewrite匹配的規(guī)則重新發(fā)起一個請求,從上到下依次匹配location后面的規(guī)則
  • proxy_pass 代理服務(wù)器

原理:Nginx攔截到相關(guān)匹配規(guī)則, Nginx再將請求轉(zhuǎn)發(fā)到http://localhost:9090,Nginx得到請求后再響應(yīng)到前端,可以直接請求/api/user完成請求。
nginx跨域請求一個簡單的dome:

server
{
    listen 80;
    server_name www.1212.com;

    location ^~ /blog/ {
        proxy_pass http://blog.12121.com/;
    }   
}

總結(jié):大功告成????????????????????????????????????????

參考鏈接:

  1. https://juejin.cn/post/6844903817595584525
  2. https://juejin.cn/post/6844904082067423246
  3. https://juejin.cn/post/6844904020360986631
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 一、Nginx是什么? 定義:Nginx (engine x) 是一個高性能的HTTP和反向代理web服務(wù)器。 從...
    今天又要上班嗎閱讀 790評論 0 0
  • Nginx與Node.js “Nginx是一款輕量級的HTTP服務(wù)器,采用事件驅(qū)動的異步非阻塞處理方式框架,這讓其...
    bayi_lzp閱讀 376評論 1 0
  • 一.跨域的定義 同源策略是一種約定,它是瀏覽器最核心也最基本的安全功能,如果缺少了同源策略,瀏覽器很容易受到XSS...
    0winder0閱讀 400評論 0 0
  • 表情是什么,我認(rèn)為表情就是表現(xiàn)出來的情緒。表情可以傳達(dá)很多信息。高興了當(dāng)然就笑了,難過就哭了。兩者是相互影響密不可...
    Persistenc_6aea閱讀 129,936評論 2 7
  • 16宿命:用概率思維提高你的勝算 以前的我是風(fēng)險厭惡者,不喜歡去冒險,但是人生放棄了冒險,也就放棄了無數(shù)的可能。 ...
    yichen大刀閱讀 8,207評論 0 4

友情鏈接更多精彩內(nèi)容