前端必備 Nginx 配置

銳玩道發表於2019-09-15
Nginx (engine x) 是一個輕量級高效能的HTTP和反向代理伺服器,同時也是一個通用 代理伺服器 (TCP/UDP/IMAP/POP3/SMTP),最初由俄羅斯人Igor Sysoev編寫。


基本命令

nginx -t             檢查配置檔案是否有語法錯誤
nginx -s reload       熱載入,重新載入配置檔案
nginx -s stop         快速關閉
nginx -s quit         等待工作程式處理完成後關閉
複製程式碼


搭建好nginx伺服器並啟動過後,我們先看nginx預設配置,再逐個介紹不同使用場景。

預設配置

Nginx 安裝目錄下, 我們複製一份`nginx.conf`成`nginx.conf.default`作為配置檔案備份,然後修改`nginx.conf`

# 工作程式的數量
worker_processes  1;
events {
    worker_connections  1024; # 每個工作程式連線數
}

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

    # 日誌格式
    log_format  access  '$remote_addr - $remote_user [$time_local] $host "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for" "$clientip"';
    access_log  /srv/log/nginx/access.log  access; # 日誌輸出目錄
    gzip  on;
    sendfile  on;

    # 連結超時時間,自動斷開
    keepalive_timeout  60;

    # 虛擬主機
    server {
        listen       8080;
        server_name  localhost; # 瀏覽器訪問域名

        charset utf-8;
        access_log  logs/localhost.access.log  access;

        # 路由
        location / {
            root   www; # 訪問根目錄
            index  index.html index.htm; # 入口檔案
        }
    }

    # 引入其他的配置檔案
    include servers/*;
}
複製程式碼


搭建站點

在其他配置檔案`servers`目錄下,新增新建站點配置檔案 xx.conf。
電腦 hosts 檔案新增  127.0.0.1   xx_domian

# 虛擬主機
server {
    listen       8080;
    server_name  xx_domian; # 瀏覽器訪問域名

    charset utf-8;
    access_log  logs/xx_domian.access.log  access;

    # 路由
    location / {
        root   www; # 訪問根目錄
        index  index.html index.htm; # 入口檔案
    }
}
複製程式碼

執行命令 nginx -s reload,成功後瀏覽器訪問  xx_domian 就能看到你的頁面


根據檔案型別設定過期時間

location ~.*\.css$ {
    expires 1d;
    break;
}
location ~.*\.js$ {
    expires 1d;
    break;
}

location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
    access_log off;
    expires 15d;    #儲存15天
    break;
}

# curl -x127.0.0.1:80 http://www.test.com/static/image/common/logo.png -I #測試圖片的max-age
複製程式碼複製程式碼


禁止檔案快取

開發環境經常改動程式碼,由於瀏覽器快取需要強制重新整理才能看到效果。這是我們可以禁止瀏覽器快取提高效率

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


防盜鏈

可以防止檔案被其他網站呼叫

location ~* \.(gif|jpg|png)$ {
    # 只允許 192.168.0.1 請求資源
    valid_referers none blocked 192.168.0.1;
    if ($invalid_referer) {
       rewrite ^/ http://$host/logo.png;
    }
}複製程式碼


靜態檔案壓縮

server {
    # 開啟gzip 壓縮
    gzip on;
    # 設定gzip所需的http協議最低版本 (HTTP/1.1, HTTP/1.0)
    gzip_http_version 1.1;
    # 設定壓縮級別,壓縮級別越高壓縮時間越長  (1-9)
    gzip_comp_level 4;
    # 設定壓縮的最小位元組數, 頁面Content-Length獲取
    gzip_min_length 1000;
    # 設定壓縮檔案的型別  (text/html)
    gzip_types text/plain application/javascript text/css;
}
複製程式碼

執行命令 nginx -s reload,成功後瀏覽器訪問

指定定錯誤頁面

# 根據狀態碼,返回對於的錯誤頁面
error_page 500 502 503 504 /50x.html;
location = /50x.html {
    root /source/error_page;
}複製程式碼

執行命令 nginx -s reload,成功後瀏覽器訪問


跨域問題

跨域的定義

同源策略限制了從同一個源載入的文件或指令碼如何與來自另一個源的資源進行互動。這是一個用於隔離潛在惡意檔案的重要安全機制。通常不允許不同源間的讀操作。

同源的定義

如果兩個頁面的協議,埠(如果有指定)和域名都相同,則兩個頁面具有相同的源。


nginx解決跨域的原理

例如:

  • 前端server域名為:http://xx_domain
  • 後端server域名為:https://github.com

現在http://xx_domainhttps://github.com發起請求一定會出現跨域。

不過只需要啟動一個nginx伺服器,將server_name設定為xx_domain,然後設定相應的location以攔截前端需要跨域的請求,最後將請求代理回github.com。如下面的配置:

## 配置反向代理的引數
server {
    listen    8080;
    server_name xx_domain

    ## 1. 使用者訪問 http://xx_domain,則反向代理到 https://github.com
    location / {
        proxy_pass  https://github.com;
        proxy_redirect     off;
        proxy_set_header   Host             $host;        # 傳遞域名
        proxy_set_header   X-Real-IP        $remote_addr; # 傳遞ip
        proxy_set_header   X-Scheme         $scheme;      # 傳遞協議
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
    }
}
複製程式碼

這樣可以完美繞過瀏覽器的同源策略:github.com訪問nginxgithub.com屬於同源訪問,而nginx對服務端轉發的請求不會觸發瀏覽器的同源策略。


如果覺得我的文章對你有用,請點贊鼓勵


相關文章