溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

nginx能用來做什么

發(fā)布時(shí)間:2022-02-17 13:49:46 來源:億速云 閱讀:123 作者:iii 欄目:開發(fā)技術(shù)

這篇“nginx能用來做什么”文章的知識點(diǎn)大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價(jià)值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“nginx能用來做什么”文章吧。

    location的匹配規(guī)則

    1. = 表示精確匹配。只有請求的url路徑與后面的字符串完全相等時(shí),才會(huì)命中。

    2. ^~ 表示如果該符號后面的字符是最佳匹配,采用該規(guī)則,不再進(jìn)行后續(xù)的查找。

    3. ~ 表示該規(guī)則是使用正則定義的,區(qū)分大小寫。

    4. ~* 表示該規(guī)則是使用正則定義的,不區(qū)分大小寫。

    注意的是,nginx的匹配優(yōu)先順序按照上面的順序進(jìn)行優(yōu)先匹配,而且注意的是一旦某一個(gè)匹配命中直接退出,不再進(jìn)行往下的匹配

    剩下的普通匹配會(huì)按照最長匹配長度優(yōu)先級來匹配,就是誰匹配的越多就用誰。

    server {
        server_name website.com;
        location /document {
            return 701;
        }
        location ~* ^/docume.*$ {
            return 702;
        }
        location ~* ^/document$ {
            return 703;
        }
    
    }
    curl -I  website.com:8080/document 702
    # 匹配702 因?yàn)檎齽t的優(yōu)先級更高,而且正則是一旦匹配到就直接退出 所以不會(huì)再匹配703
    server {
        server_name website.com;
        location ~* ^/docume.*$ {
            return 701;
        }
    
        location ^~ /doc {
            return 702;
        }
        location ~* ^/document$ {
            return 703;
        }
    }
    curl http://website.com/document
    HTTP/1.1 702
    # 匹配702 因?yàn)?nbsp;^~精確匹配的優(yōu)先級比正則高 也是匹配到之后支持退出
    server {
        server_name website.com;
        location /doc {
            return 702;
        }
        location /docu {
            return 701;
        }
    }
    # 701 前綴匹配匹配是按照最長匹配,跟順序無關(guān)

    history模式、跨域、緩存、反向代理

    # html設(shè)置history模式
    location / {
        index index.html index.htm;
        proxy_set_header Host $host;
        # history模式最重要就是這里
        try_files $uri $uri/ /index.html;
        # index.html文件不可以設(shè)置強(qiáng)緩存 設(shè)置協(xié)商緩存即可
        add_header Cache-Control 'no-cache, must-revalidate, proxy-revalidate, max-age=0';
    }
    
    # 接口反向代理
    location ^~ /api/ {
        # 跨域處理 設(shè)置頭部域名
        add_header Access-Control-Allow-Origin *;
        # 跨域處理 設(shè)置頭部方法
        add_header Access-Control-Allow-Methods 'GET,POST,DELETE,OPTIONS,HEAD';
        # 改寫路徑
        rewrite ^/api/(.*)$ /$1 break;
        # 反向代理
        proxy_pass http://static_env;
        proxy_set_header Host $http_host;
    }
    
    location ~* \.(?:css(\.map)?|js(\.map)?|gif|svg|jfif|ico|cur|heic|webp|tiff?|mp3|m4a|aac|ogg|midi?|wav|mp4|mov|webm|mpe?g|avi|ogv|flv|wmv)$ {
        # 靜態(tài)資源設(shè)置七天強(qiáng)緩存
        expires 7d;
        access_log off;
    }

    以目錄去區(qū)分多個(gè)history單文件

    因?yàn)椴豢赡苊恳粋€(gè)項(xiàng)目開啟一個(gè)域名,僅僅指向通過增加路徑來劃分多個(gè)網(wǎng)站,比如:

    1. www.taobao.com/tmall/login訪問天貓的登錄頁面

    2. www.taobao.com/alipay/login訪問支付寶的登錄頁面

    server {
        listen 80;
        server_name taobao.com;
        index index.html index.htm;
        # 通過正則來匹配捕獲 [tmall|alipay]中間的這個(gè)路徑
        location ~ ^/([^\/]+)/(.*)$ {
            try_files $uri $uri/ /$1/dist/index.html =404;
        }
    }

    負(fù)載均衡

    基于upstream做負(fù)載均衡,中間會(huì)涉及一些相關(guān)的策略比如ip_hash、weight

    upstream backserver{ 
        # 哈希算法,自動(dòng)定位到該服務(wù)器 保證唯一ip定位到同一部機(jī)器 用于解決session登錄態(tài)的問題
        ip_hash; 
        server 127.0.0.1:9090 down; (down 表示單前的server暫時(shí)不參與負(fù)載) 
        server 127.0.0.1:8080 weight=2; (weight 默認(rèn)為1.weight越大,負(fù)載的權(quán)重就越大) 
        server 127.0.0.1:6060; 
        server 127.0.0.1:7070 backup; (其它所有的非backup機(jī)器down或者忙的時(shí)候,請求backup機(jī)器) 
    }

    灰度部署

    如何根據(jù)headers頭部來進(jìn)行灰度,下面的例子是用cookie來設(shè)置

    如何獲取頭部值在nginx中可以通過$http_xxx來獲取變量

    upstream stable {
        server xxx max_fails=1 fail_timeout=60;
        server xxx max_fails=1 fail_timeout=60;
     }
    upstream canara {
       server xxx max_fails=1 fail_timeout=60;
    }
    
    server {
        listen 80;
        server_name  xxx;
        # 設(shè)置默認(rèn)
        set $group "stable";
    
        # 根據(jù)cookie頭部設(shè)置接入的服務(wù)
        if ($http_cookie ~* "tts_version_id=canara"){
            set $group canara;
        }
        if ($http_cookie ~* "tts_version_id=stable"){
            set $group stable;
        }
        location / {
            proxy_pass http://$group;
            proxy_set_header   Host             $host;
            proxy_set_header   X-Real-IP        $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            index  index.html index.htm;
        }
    }

    優(yōu)雅降級

    常用于ssr的node服務(wù)掛了返回500錯(cuò)誤碼然后降級到csr的cos桶或者nginx中

    優(yōu)雅降級主要用error_page參數(shù)來進(jìn)行降級指向備用地址。

    upstream ssr {
        server xxx max_fails=1 fail_timeout=60;
        server xxx max_fails=1 fail_timeout=60;
     }
    upstream csr {
        server xxx max_fails=1 fail_timeout=60;
        server xxx max_fails=1 fail_timeout=60;
    }
    
    location ^~ /ssr/ {
        proxy_pass http://ssr;
        # 開啟自定義錯(cuò)誤捕獲 如果這里不設(shè)置為on的話 會(huì)走向nginx處理的默認(rèn)錯(cuò)誤頁面
        proxy_intercept_errors on;
        # 捕獲500系列錯(cuò)誤 如果500錯(cuò)誤的話降級為下面的csr渲染
        error_page 500 501 502 503 504 = @csr_location
    
        # error_page 500 501 502 503 504 = 200 @csr_location
        # 注意這上面的區(qū)別 等號前面沒有200 表示 最終返回的狀態(tài)碼已 @csr_location為準(zhǔn) 加了200的話表示不管@csr_location返回啥都返回200狀態(tài)碼
    }
    
    location @csr_location {
        # 這時(shí)候地址還是帶著/ssr/的要去除
        rewrite ^/ssr/(.*)$ /$1 break;
        proxy_pass http://csr;
        rewrite_log on;
    }

    webp根據(jù)瀏覽器自動(dòng)降級為png

    這套方案不像常見的由nginx把png轉(zhuǎn)為webp的方案,而是先經(jīng)由圖床系統(tǒng)(node服務(wù))上傳兩份圖片:

    1. 一份是原圖png

    2. 一份是png壓縮為webp的圖片(使用的是imagemin-webp)

    然后通過nginx檢測頭部是否支持webp來返回webp圖片,不支持的話就返回原圖即可。這其中還做了錯(cuò)誤攔截,如果cos桶丟失webp圖片及時(shí)瀏覽器支持webp也要降級為png

    http {
      include       /etc/nginx/mime.types;
      default_type  application/octet-stream;
    
      # 設(shè)置日志格式
      log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
      '$status $body_bytes_sent "$http_referer" '
      '"$http_user_agent" "$http_x_forwarded_for"'
      '"$proxy_host" "$upstream_addr"';
    
      access_log  /var/log/nginx/access.log  main;
    
      sendfile        on;
      keepalive_timeout  65;
    
      # 開啟gzip
      gzip on;
      gzip_vary on;
      gzip_proxied any;
      gzip_comp_level 6;
      gzip_types text/plain text/css text/xml application/json application/javascript application/rss+xml application/atom+xml image/svg+xml;
    
      # 負(fù)載均衡 這里可以是多個(gè)cos桶地址即可
      upstream static_env {
        server xxx;
        server xxx;
      }
    
      # map 設(shè)置變量映射 第一個(gè)變量指的是要通過映射的key值 Accpet 第二個(gè)值的是變量別名
      map $http_accept $webp_suffix {
        # 默認(rèn)為 空字符串
        default   "";
        # 正則匹配如果Accep含有webp字段 設(shè)置為.webp值
        "~*webp"  ".webp";
      }
      server {
    
        listen 8888;
        absolute_redirect off;    #取消絕對路徑的重定向
        #網(wǎng)站主頁路徑。此路徑僅供參考,具體請您按照實(shí)際目錄操作。
        root /usr/share/nginx/html;
    
        location / {
          index index.html index.htm;
          proxy_set_header Host $host;
          try_files $uri $uri/ /index.html;
          add_header Cache-Control 'no-cache, max-age=0';
        }
    
        # favicon.ico
        location = /favicon.ico {
          log_not_found off;
          access_log off;
        }
    
        # robots.txt
        location = /robots.txt {
          log_not_found off;
          access_log off;
        }
    
        # 
        location ~* \.(png|jpe?g)$ {
          # Pass WebP support header to backend
          # 如果header頭部中支持webp
          if ($webp_suffix ~* webp) {
            # 先嘗試找是否有webp格式圖片
            rewrite ^/(.*)\.(png|jpe?g)$ /$1.webp break;
            # 找不到的話 這里捕獲404錯(cuò)誤 返回原始錯(cuò)誤 注意這里的=號 代表最終返回的是@static_img的狀態(tài)嗎
            error_page 404 = @static_img;
          }
          proxy_intercept_errors on;
          add_header Vary Accept;
          proxy_pass http://static_env;
          proxy_set_header Host $http_host;
          expires 7d;
          access_log off;
        }
    
        location @static_img {
          #set $complete $schema $server_addr $request_uri;
          rewrite ^/.+$ $request_uri break;
          proxy_pass http://static_env;
          proxy_set_header Host $http_host;
          expires 7d;
        }
    
    
        # assets, media
        location ~* \.(?:css(\.map)?|js(\.map)?|gif|svg|jfif|ico|cur|heic|webp|tiff?|mp3|m4a|aac|ogg|midi?|wav|mp4|mov|webm|mpe?g|avi|ogv|flv|wmv)$ {
          proxy_pass http://static_env;
          proxy_set_header Host $http_host;
          expires 7d;
          access_log off;
        }
    
    
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
          root   /usr/share/nginx/html;
        }
      }
    }

    為什么要用nginx,nginx有什么特點(diǎn)?

    nginx的特點(diǎn):

    • 核心特點(diǎn):高并發(fā)請求的同時(shí)保持高效的服務(wù)

    • 熱部署

    • 低內(nèi)存消耗

    • 處理響應(yīng)請求很快

    • 具有很高的可靠性

    同時(shí),nginx也可以實(shí)現(xiàn)高效的反向代理、負(fù)載均衡。

    前端可以用nginx做些什么?

    • 搭建靜態(tài)資源服務(wù)器

    • 反向代理分發(fā)后端服務(wù)(可以和nodejs搭配實(shí)現(xiàn)前后端分離)和跨域問題

    • 根據(jù)User Agent來重定向站點(diǎn)

    • 開發(fā)環(huán)境或測試環(huán)境切換(切換host)

    • url重寫,使用rewrie規(guī)則本地映射

    • 資源內(nèi)容篡改

    • 獲取cookie做分流

    • 資源合并

    • gzip壓縮

    • 壓縮圖片

    • sourceMap調(diào)試

    以上就是關(guān)于“nginx能用來做什么”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對大家有幫助,若想了解更多相關(guān)的知識內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道。

    向AI問一下細(xì)節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI