1. 程式人生 > >Nginx靜態資源部署

Nginx靜態資源部署

前言:

傳統的web專案,一般都將靜態資源連同專案部署在容器中(如tomcat、jetty),但是有時需要把這些靜態資原始檔單獨拿出來,ngnix這時可以來充當靜態資源伺服器的功能。

配置Nginx/Tengine

請先確保自己的伺服器安裝了Nginx或者Tengine(本文以Tengine為例)

  • 將靜態資原始檔拷貝到指定目錄,如/home/admin

  • 配置nginx-proxy.conf檔案

 server {
        listen       8089;
        server_name  localhost;
        location /resource_static/
{ root /home/admin/; } }

本文配置的監聽埠為8089,具體是情況而定

  • 測試驗證

上面配置表示輸入 localhost:8089/resource_static/ 時會訪問本機的/home/admin/resource_static/ 目錄,在/home/admin/resource_static/下新建一個檔案test.json,如下所示:

這裡寫圖片描述

在瀏覽器中輸入:

localhost:8089/resource_static/test.json

跨域問題

跨域問題經常會遇到,如下面的錯誤:

Access to Font at 'http://xxx:8089/resource_static/console/hello.ttf'
from origin 'http://xxx:8089' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://xxx:8080' is therefore not allowed access.

解決方法:

        location /resource_static/ {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Credentials'
'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; root /home/admin/; }

如果配置成這樣,依然會有問題

        location /resource_static/ {
            root   /home/admin/;
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
        }