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/;
        }

參考資料https://michielkalkman.com/snippets/nginx-cors-open-configuration.html

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

        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';
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章