首页 > 解决方案 > docker nginx没有加载css样式

问题描述

使用 Nginx 作为 Web 服务器将静态文件上传到我的服务器时,我的 css、javascript 和 google 字体无法像在 localhost 上测试站点时那样工作。

我正在使用基本映像在 docker 容器中运行 Nginx。
Dockerfile

FROM nginx
COPY example.com.conf /etc/nginx/nginx.conf
COPY build /etc/nginx/html/

nginx.conf

user nginx;

events {
  worker_connections  4096;  ## Default: 1024
}

http {
  server {
    listen 80;
    listen [::]:80;

    server_name example.com;

    include /etc/nginx/mime.types;
    root /etc/nginx/html;
    index index.html;

    location ~ \.css {
      add_header  Content-Type    text/css;
    }
    location ~ \.js {
      add_header  Content-Type    application/x-javascript;
    }

    location / {
      try_files $uri /index.html =404;
    }
  }
}

有人可以告诉我我的conf有什么问题吗?

同样,当在 Chrome 上查看时,控制台也会记录这一点Resource interpreted as Stylesheet but transferred with MIME type text/plain

我看过的其他一些 SO 帖子:
SO post
SO post

标签: dockernginxdockerfilenginx-config

解决方案


在这个SO 答案和评论的帮助下,我能够让它工作。如果我的回答对您没有帮助,我建议您在 docker 容器中运行 Nginx 时查看该问题。

对我来说,它正在移动include /etc/nginx/mime.types;并添加sendfile on; 到我server的块之外和http块中

我的 example.com.conf 现在看起来像这样:

user nginx;

events {
  worker_connections  4096;  ## Default: 1024
}

http {

  include /etc/nginx/mime.types;
  sendfile on;

  server {
    listen 80;
    listen [::]:80;

    server_name example.com;

    root /etc/nginx/html;
    index index.html;

    location ~ \.css {
      add_header  Content-Type    text/css;
    }
    location ~ \.js {
      add_header  Content-Type    application/x-javascript;
    }

    location / {
      try_files $uri /index.html =404;
    }
  }
}

推荐阅读