Nginx不能在简单的PHP项目中正确地提供CSS

我已经看到了几个这样的例子: Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost:3001/assets/css/bootstrap.min.css" 。 但是,我一直不明白是什么原因造成的。

我简单的PHP项目中的CSS文件没有被服务。 状态代码是200 ,文件确实加载,其内容可以从开发者控制台查看。 我也检查了/etc/nginx/mime.types文件,它有一个text/css的条目。 最后,这是我的网站configuration:

 server { listen 3001 default_server; listen [::]:3001 default_server; server_name _; location / { root /media/common/code/projects/newdf; try_files $uri $uri/ =404; include fastcgi_params; fastcgi_index index.php; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/run/php/php7.0-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name; } } 

即使在代码中,HTML标签也将其types指定为text/css

 <link rel="stylesheet" type="text/css" href="<?php echo $server_url; ?>/assets/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="<?php echo $server_url; ?>/assets/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="<?php echo $server_url; ?>/assets/css/animate.css"> <link rel="stylesheet" type="text/css" href="<?php echo $server_url; ?>/assets/css/style.css"> 

我不知道发生了什么事情。

有趣的是,JS文件加载没有错误,如果我在内置的PHP服务器上运行该网站,没有任何问题。

根本问题是,你通过php-fpm提供所有的内容,包括静态内容和dynamic内容。 通常,允许nginx提供静态内容,在这种情况下, nginx负责根据文件扩展名设置Content-Type头。

在您当前的configuration中,所有内容都传递给php-fpm并接收默认的Content-Type text/html 。 推测你已经禁用security.limit_extensions使这个工作。

您可以使用两个location块,一个用于静态内容,另一个用于dynamic内容。 以下是基于你的问题和这个来自nginx wiki的例子 :

 server { listen 3001 default_server; listen [::]:3001 default_server; root /media/common/code/projects/newdf; index index.php; location / { try_files $uri $uri/ =404; } location ~ [^/]\.php(/|$) { fastcgi_split_path_info ^(.+?\.php)(/.*)$; if (!-f $document_root$fastcgi_script_name) { return 404; } include fastcgi_params; fastcgi_index index.php; fastcgi_pass unix:/run/php/php7.0-fpm.sock; fastcgi_param HTTP_PROXY ""; fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name; } } 

编辑:为不需要path信息的应用程序添加了以下简化示例:

 server { listen 3001 default_server; listen [::]:3001 default_server; root /media/common/code/projects/newdf; index index.php; location / { try_files $uri $uri/ =404; } location ~ \.php$ { try_files $uri =404; include fastcgi_params; fastcgi_pass unix:/run/php/php7.0-fpm.sock; fastcgi_param HTTP_PROXY ""; fastcgi_param SCRIPT_FILENAME $request_filename; } }