前端必備 Nginx 配置
1、Nginx 默認配置
# 工作進程的數量
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 /var/log/nginx/access.log; # 日誌輸出目錄
gzip on;
sendfile on;
# 鏈接超時時間,自動斷開
keepalive_timeout 60;
# 虛擬主機
server {
listen 80;
server_name localhost; # 瀏覽器訪問域名
charset utf-8;
access_log /var/log/nginx/access.log access;
# 路由
location / {
root www; # 訪問根目錄
index index.html index.htm; # 入口文件
}
}
# 引入其他的配置文件
include servers/*;
}
2、根據文件類型設置過期時間
location ~.*\.css$ {
expires 1d;
break;
}
location ~.*\.js$ {
expires 1d;
break;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
access_log off;
expires 15d; #保存15天
break;
}
3、禁止文件緩存
開發環境經常改動代碼,由於瀏覽器緩存需要強制刷新才能看到效果,這時候我們可以禁止瀏覽器緩存提高訪問效率
location ~* \.(js|css|png|jpg|gif)$ {
add_header Cache-Control no-store;
}
4、防盜鏈
可以防止文件被其他網站調用
location ~* \.(gif|jpg|png)$ {
valid_referers none blocked 192.168.182.1; # 只允許 192.168.182.1 請求資源
if ($invalid_referer) {
rewrite ^/ http://$host/logo.png; # 無效引用者轉發至該鏈接
}
}
5、靜態文件壓縮
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;
}
6、指定定錯誤頁面
# 根據狀態碼,返回對於的錯誤頁面
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /source/error_page;
}
7、跨域問題
跨域的定義
- 同源策略限制了從同一個源加載的文檔或腳本如何與來自另一個源的資源進行交互。
- 這是一個用於隔離潛在惡意文件的重要安全機制。通常不允許不同源間的讀操作。
同源的定義
- 如果兩個頁面的協議,端口(如果有指定)和域名都相同,則兩個頁面具有相同的源。
nginx解決跨域的原理
例如:
- 前端server域名爲:
http://xx_domain
- 後端server域名爲:
https://github.com
現在http://xx_domain
對https://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
訪問nginx的github.com
屬於同源訪問,而nginx對服務端轉發的請求不會觸發瀏覽器的同源策略。
https://juejin.im/post/5d7e49c8f265da03ce3a0884