【问题标题】:docker nginx not loading css stylesdocker nginx没有加载css样式
【发布时间】:2021-06-27 10:09:37
【问题描述】:

当使用 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

【问题讨论】:

    标签: docker nginx dockerfile nginx-config


    【解决方案1】:

    SO answer 和 cmets 的帮助下,我能够让它工作。如果我的回答对你没有帮助,我建议你在 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;
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-01
      • 1970-01-01
      • 2021-06-04
      相关资源
      最近更新 更多