Nginx静态资源部署

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ouyang111222/article/details/53266107

前言:

传统的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';
        }

猜你喜欢

转载自blog.csdn.net/ouyang111222/article/details/53266107