Nginx 在简单的 PHP 项目中无法正确提供 CSS

ank*_*981 5 nginx static-content php-fpm

我现在已经看到了几个这样的例子: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. 最后,这是我的网站配置:

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;
    }   
}
Run Code Online (Sandbox Code Playgroud)

即使在代码中,HTML 标记也将类型指定为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">
Run Code Online (Sandbox Code Playgroud)

我不知道发生了什么事。

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

Ric*_*ith 4

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

在您当前的配置中,所有内容都会传递到php-fpm并接收默认Content-Typetext/html。想必您已禁用security.limit_extensions此功能。

您可以使用两个location块,一个用于静态内容,一个用于动态内容。以下内容基于您的问题和wiki中的示例nginx

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;
    }   
}
Run Code Online (Sandbox Code Playgroud)

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

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;
    }   
}
Run Code Online (Sandbox Code Playgroud)