【问题标题】:Nginx try_files doesn't work 404, cannot load filesNginx try_files 不起作用 404,无法加载文件
【发布时间】:2019-03-15 06:26:11
【问题描述】:

我已经处理了这个问题大约几个小时,但没有任何成功。 我无法从我的项目中提供静态文件的问题。

以前我对 Apache 服务器有以下规则。

RewriteRule ^assets/(.*)$ /web/assets/$1 [L]
RewriteRule ^css/(.*)$ web/css/$1 [L]
RewriteRule ^js/(.*)$ web/js/$1 [L]
RewriteRule ^images/(.*)$ web/images/$1 [L]

我在我的 nginx 配置中尝试了以下位置规则

  location ~ ^/css/?(.*)$ {
        #return 200 $document_root/web/css/$1;
        # kill cache
        add_header Last-Modified $date_gmt;
        add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        if_modified_since off;
        expires off;
        etag off;
       #try_files $uri $uri/ /index.php =404;
       try_files $document_root/web/css/$1 =404;
    }

顺便说一句,#return 200 $document_root/web/css/$1; 返回有效路径。

但请求仍然失败。

我也尝试如下使用alias

  location ~ ^/css/?(.*)$ {
        alias /var/wwww/myproject/web/css;
        # kill cache
        add_header Last-Modified $date_gmt;
        add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        if_modified_since off;
        expires off;
        etag off;
        try_files $uri $uri/ /index.php =404;
    }

同样的情况404,如果我在上面的位置更改404它也会返回另一个代码,因此到达位置语句但try_files不起作用

请帮助解决问题,我不知道该尝试什么。 谢谢

【问题讨论】:

    标签: nginx nginx-location static-files nginx-config


    【解决方案1】:

    如果您的文件路径可以通过将root 的值与当前URI 连接来构建,则您应该使用root 而不是alias。详情请见this document。

    假设/css/foo.css 实际位于/var/www/myproject/web/css/foo.css,以下示例就足够了。

    location /css/ {
        root /var/www/myproject/web;
        ...
        try_files $uri $uri/ /index.php;
    }
    

    您不需要使用正则表达式location,也不需要捕获部分URI。

    try_files 语句需要以=404 或/index.php 结尾,不能同时以两者结尾。有关详细信息,请参阅this document。

    【讨论】:

    • 感谢您的回答!它可以工作,但是为了让它工作,我必须在位置路径前面加上~。您能解释一下为什么我的变体不起作用吗?
    • 如果您需要使用正则表达式位置,下面可能有另一个冲突的正则表达式位置块-例如location \.css。您可以改用location ^~ /css/,它仍然是前缀位置,但优先于所有正则表达式位置。详情请见this document。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-01
    • 2014-08-19
    • 2012-04-24
    • 2016-02-09
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    相关资源
    最近更新 更多