Nginx 加载 css 文件失败

我最近决定从 apache2切换到 Nginx。我在 CentOS 服务器上安装了 Nginx,并设置了一个基本配置。 当我试图在浏览器中加载我的网站(FF/Chrome)时,我注意到 css 文件没有加载。我检查了错误控制台,看到如下消息:

Error: The stylesheet http://example.com/style.css was not loaded because its MIME type, "text/html", is not "text/css".

我检查了 Nginx 配置,一切似乎都很正常:

http {
include /etc/nginx/mime.types;
..........
}

Css 文件的 mime 类型在/etc/nginx/ime.type 中设置正确。

text/css css;

一切似乎配置良好,但我的 css 文件仍然没有加载。我没有解释。

另一件值得一提的事。最初我使用 epel 软件库安装了 Nginx,得到了一个旧版本: 0.8... ... 在我看来,我的问题出在那个版本的 bug 上,所以我卸载了0.8版本,将 Nginx 软件库添加到 yum,然后安装了最新版本: 1.0.14。我以为新版本会解决我的问题,但不幸的是,它没有,所以我跑出来的想法。

谢谢你的帮助。

配置文件:

/etc/nginx/nginx.conf

user  nginx;
worker_processes  1;


error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;




events {
worker_connections  1024;
}




http {
include       /etc/nginx/mime.types;
default_type  application/octet-stream;


log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';


access_log  /var/log/nginx/access.log  main;


sendfile        on;
#tcp_nopush     on;


keepalive_timeout  65;


#gzip  on;


include /etc/nginx/conf.d/*.conf;
}

/etc/nginx/conf. d/default.conf

server {
listen       80;
server_name  localhost;


#charset koi8-r;
#access_log  /var/log/nginx/log/host.access.log  main;


location / {
root    /usr/share/nginx/html;
index  index.html index.htm index.php;
fastcgi_pass   127.0.0.1:9000;
fastcgi_index  index.php;
fastcgi_param  SCRIPT_FILENAME  /usr/share/nginx/html$fastcgi_script_name;
include        fastcgi_params;
}


#error_page  404              /404.html;


# redirect server error pages to the static page /50x.html
#
error_page   500 502 503 504  /50x.html;
location = /50x.html {
root   /usr/share/nginx/html;
}


# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
#    proxy_pass   http://127.0.0.1;
#}


# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
#    root           html;
#    fastcgi_pass   127.0.0.1:9000;
#    fastcgi_index  index.php;
#    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
#    include        fastcgi_params;
#}


# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
#    deny  all;
#}
}

/etc/nginx/mime. type

types {
text/html                             html htm shtml;
text/css                              css;
text/xml                              xml;
image/gif                             gif;
image/jpeg                            jpeg jpg;
application/x-javascript              js;
application/atom+xml                  atom;
application/rss+xml                   rss;
..........................................
other types here
..........................................
}
196852 次浏览

I found an workaround on the web. I added to /etc/nginx/conf.d/default.conf the following:

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

The problem now is that a request to my css file isn't redirected well, as if root is not correctly set. In error.log I see

2012/04/11 14:01:23 [error] 7260#0: *2 open() "/etc/nginx//html/style.css"

So as a second workaround I added the root to each defined location. Now it works, but seems a little redundant. Isn't root inherited from / location ?

Putting the include /etc/nginx/mime.types; under location / { instead of under http { solved the issue for me.

I ran into this issue too. It confused me until I realized what was wrong:

You have this:

include       /etc/nginx/mime.types;
default_type  application/octet-stream;

You want this:

default_type  application/octet-stream;
include       /etc/nginx/mime.types;

there appears to either be a bug in nginx or a deficiency in the docs (this could be the intended behavior, but it is odd)

style.css is actually being process via fastcgi due to your "location /" directive. So it is fastcgi that is serving up the file (nginx > fastcgi > filesystem), and not the filesystem directly (nginx > filesystem).

For a reason I have yet to figure out (I'm sure there's a directive somewhere), NGINX applies the mime type text/html to anything being served from fastcgi, unless the backend application explicitly says otherwise.

The culprit is this configuration block specifically:

location / {
root    /usr/share/nginx/html;
index  index.html index.htm index.php;
fastcgi_pass   127.0.0.1:9000;
fastcgi_index  index.php;
fastcgi_param  SCRIPT_FILENAME  /usr/share/nginx/html$fastcgi_script_name;
include        fastcgi_params;
}

It should be:

location ~ \.php$ { # this line
root    /usr/share/nginx/html;
index  index.html index.htm index.php;
fastcgi_split_path_info ^(.+\.php)(/.+)$; #this line
fastcgi_pass   127.0.0.1:9000;
fastcgi_index  index.php;
fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name; # update this too
include        fastcgi_params;
}

This change makes sure only *.php files are requested from fastcgi. At this point, NGINX will apply the correct MIME type. If you have any URL rewriting happening, you must handle this before the location directive (location ~\.php$) so that the correct extension is derived and properly routed to fastcgi.

Be sure to check out this article regarding additional security considerations using try_files. Given the security implications, I consider this a feature and not a bug.

I followed some tips from the rest answers and discovered that these odd actions helped (at least in my case).

1) I added to server block the following:

location ~ \.css {
add_header Content-Type text/css;
}

I reloaded nginx and got this in error.log:

2015/06/18 11:32:29 [error] 3430#3430: *169 open() "/etc/nginx/html/css/mysite.css" failed (2: No such file or directory)

2) I deleted the rows, reloaded nginx and got working css. I can't explain what happend because my conf file became such as before.

My case was clean xubuntu 14.04 on VirtualBox, nginx/1.9.2, a row 127.51.1.1 mysite in /etc/hosts and pretty simple /etc/nginx/nginx.conf with a server block:

user nginx;
worker_processes 1;


error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;


events {
worker_connections  1024;
}


http {
include /etc/nginx/mime.types;


server {
listen 80;
server_name mysite;


location / {
root /home/testuser/dev/mysite/;
}
}
}

add this to your ngnix conf file

add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://ssl.google-analytics.com https://assets.zendesk.com https://connect.facebook.net; img-src 'self' https://ssl.google-analytics.com https://s-static.ak.facebook.com https://assets.zendesk.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://assets.zendesk.com; font-src 'self' https://themes.googleusercontent.com; frame-src https://assets.zendesk.com https://www.facebook.com https://s-static.ak.facebook.com https://tautt.zendesk.com; object-src 'none'";

I had the same problem in Windows. I solved it adding: include mime.types; under http{ in my nginx.conf file. Then it still didn't work.. so I looked at the error.log file and I noticed it was trying to charge the .css and javascript files from the file path but with an /http folder between. Ex: my .css was in : "C:\Users\pc\Documents\nginx-server\player-web\css\index.css" and it was taking it from: "C:\Users\pc\Documents\nginx-server*html*\player-web\css\index.css" So i changed my player-web folder inside an html folder and it worked ;)

I actually took my time went through all the above answers on this page but to no avail. I just happened to change the owner and the permissions of directory and sub-directories using the following command.I changed the owner of the web project directory in /usr/share/nginx/html to the root user using:

chown root /usr/share/nginx/html/mywebprojectdir/*

And finally changed the permissions of that directory and sub-directories using:

chmod 755 /usr/share/nginx/html/mywebprojectdir/*

NOTE: if denied , you can use sudo

I was having the same issue and none of the above made any difference for me what did work was having my location php above any other location blocks.

location ~ [^/]\.php(/|$) {
fastcgi_split_path_info  ^(.+\.php)(/.+)$;
fastcgi_index            index.php;
fastcgi_pass             unix:/var/run/php/php7.3-fpm.sock;
include                  fastcgi_params;
fastcgi_param   PATH_INFO       $fastcgi_path_info;
fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
** The below is specifically for moodle **
location /dataroot/ {
internal;
alias <full_moodledata_path>; # ensure the path ends with /
}

I also face this issue, I tried a lot of solutions, but none really worked for me

Here's how I solved it;

A. Grant ownership of the domain document root directory (say my root directory is/var/www/nginx-demo) to the Nginx user (www-data) to avoid any permission issues:

sudo chown -R www-data: /var/www/nginx-demo

B. Confirm that your virtual host server block conforms to this standard (say I am using localhost as my server_name and my root as /var/www/nginx-demo/website)

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


server_name localhost;


root /var/www/nginx-demo/website;
index index.html;


location / {
try_files $uri $uri/ =404;
}
}

C. Test the Nginx configuration for correct syntax:

sudo nginx -t

If there are no errors in the configuration syntax the output will look like this:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

D. Restart the Nginx service for the changes to take effect:

sudo systemctl restart nginx

E. Hard refresh your website in your browser to avoid cached files with incorrect headers using the keyboard keys Ctrl + F5 or Ctrl + Fn + F5.

That's all.

I hope this helps.

  1. In your nginx.conf file, add mime.types to your http body like so:

    http {
    include /etc/nginx/mime.types;
    include /etc/nginx/conf.d/*.conf;
    }
    
  2. Now go to the terminal and run the following to reload the server:

    sudo nginx -s reload
    
  3. Open your web browser and do a hard reload: Right click on the reload button and select hard reload. On Chrome you can do Ctrl+Shift+R

For me this was ad blocker installed on web browser. It was not letting load the style.css

The same problem came up with Nginx 1.14.2 on Debian 10.6.

It can be resolved by setting the charset variable. By adding to the server block, beneath the server_name directive the following:

charset utf-8; # Use the appropriate charset in place of "utf-8"

After also trying for hours my case was different from all others here. It was a dot in one of the folders of the path that I used as a hidden folder for the resources:

<link type = "text/css" href="../../.res/css/bootstrap.min.css" rel="stylesheet">

That was causing that the styles weren't rendered in the browser although they were being loaded with no errors from nginx. Only Firefox (not Chrome) complained about MIME types of css not being css but text.

I know this IS late, but after scouring the internet for solutions and while all were concentrated on the config, actually the html itself is as Importnant

on the config side and after you've defined your project root, you should point to your statrics especially css in this case like this for example - I have my css in root/src

location ~*/src/.css {
include /etc/nginx/mime.types;
add_header Content-type text/css;
}

and in you HTML: make sure to use the rel and the type properly

<link rel="stylesheet" href="src/styles.css" type="text/css">

hope this helps others in the future