【问题标题】:Static files getting 404 with nginx proxy使用 nginx 代理获取 404 的静态文件
【发布时间】:2020-10-07 08:26:40
【问题描述】:

我已将 nginx 配置为提供静态页面,如下所示。

       location /home {
                alias /home/username/files/home;
                try_files $uri /home/index.html;
        }

http://example.com/home 上仅加载 index.html。所有其他 css、js 和图像文件都得到 404,因为请求仍然是 http://example.com/css/style.css 而不是 http://example.com/home/css/style.css。有什么方法可以为所有静态文件配置/home前缀,而无需手动添加到所有静态文件中?

【问题讨论】:

  • 在答案中添加了重要说明,请查看答案编辑历史记录。

标签: nginx


【解决方案1】:

您可以尝试根据 HTTP Referer 标头使用变量根(虽然这是一个肮脏的黑客):

map $http_referer $root {
    ~example\.com/home/    /home/username/files/home;
    default                <your default root here>;
}

server {
    ...
    root $root;

    location /home {
        root /home/username/files;
        try_files $uri /home/index.html;
    }
}

请注意,如果您在/home/ 下的任何网页都有指向主站点的链接,则这些链接将无法正常工作,因为example.com/home/... HTTP 引用标头值。

你问为什么是root /home/username/files; 而不是alias /home/username/files/home;?因为作为 nginx 文档states:

当位置与指令值的最后一部分匹配时:

location /images/ {
    alias /data/w3/images/;
}

最好改用root 指令:

location /images/ {
    root /data/w3;
}

【讨论】:

  • 现在这个 hack 有效。仅从 /home/ 链接到主站点 example.com 本身。
猜你喜欢
  • 2015-12-01
  • 2016-08-19
  • 2015-02-26
  • 2017-10-27
  • 2021-01-12
  • 2014-06-07
  • 2014-12-01
  • 2017-06-05
  • 1970-01-01
相关资源
最近更新 更多