nginx vhost,问题服务.css作为静态文件或动态文件

时间:2019-12-06 13:10:00

标签: nginx

我在满足要求时遇到问题: 我想要两件事;

  1. https://www.test-boutique.vm/store.css将被路由到PHP应用程序,因为文件内容是由应用程序流式传输的;
  2. https://www.test-boutique.vm/static/css/basic.css,因为它存在于文件系统中;

我的虚拟主机是:

server {
    listen 443;

    server_name www.test-boutique.vm;

    root /srv/app/public/front;
    index index.php;


    location / {
        # try to serve file directly, fallback to index.php
        try_files $uri $uri/ /index.php$is_args$args;
    }

    # css are for the files generated by the application (store.css)
    location ~ \.(php|htm|css)$ {
        try_files $uri $uri/ /index.php$is_args$args;
        fastcgi_pass unix:/var/run/php-fpm.app.sock;
        fastcgi_index index.php;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        fastcgi_param HTTPS on;
        fastcgi_param APP_ENV dev;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~* \.(js|css|bmp|png|jpg|jpeg|gif|swf|ico)$ {
        try_files $uri =404;
        log_not_found off;
        access_log off;
        expires 7d;
        add_header Cache-Control public;
        add_header Cache-Control must-revalidate;
    }

   rewrite ^/media/(.*)$ https://test.cloud/$http_host/media/$1 permanent;
   rewrite ^/img/(.*)$ https://test.cloud/$http_host/img/$1 permanent;

  access_log /var/log/nginx/fov4_access_log;
  error_log /var/log/nginx/fov4_error_log;
}

使用此版本:

  1. /store.css文件运行良好(由PHP应用程序生成)
  2. /static/css/basic.css试图由PHP应用程序提供服务,而不是直接从文件系统提供文件(文件肯定在此路径下存在)

从虚拟主机中删除css部分时 ({location ~ \.(php|htm|css)$ { 新建 location ~ \.(php|htm)$ {

  1. /store.css文件正试图用作静态资产,并最终显示404(请求未传递到应用程序)
  2. /static/css/basic.css投放正确

我想念什么?

1 个答案:

答案 0 :(得分:1)

与其像在这里一样匹配所有css文件,location ~ \.(php|htm|css)$ {,而是尝试匹配PHP需要生成的一个css文件:

location ~ \.(php|htm)$ {
  # you php-fpm config here
}

location ~* \.(js|css|bmp|png|jpg|jpeg|gif|swf|ico)$ {
   # your static files config here
}

location = /store.css {
   # you php-fpm config here
}