nginx 返回静态文件配置问题

2020-08-24 18:05:49 +08:00
 GGGG430

如题, 目前网上搜索找到了以下两种方式返回静态文件

server {
    location ~ ^/a {
        default_type text/html;
        return 200 'asdfasdfasdfasdf';
    }
    
    location ~ ^/b {
        default_type application/json;
        add_header Content-Type 'text/html; charset=utf-8';
        alias /tmp/b.json;
    }
    
    if ($var = true) {
        return 200 "asdf";
    }
}

那么有没有办法在 if 结构中返回一个指定路径的文件内容呢, 而不是一个固定的字符串, 如下伪代码

server {
    if ($var = true) {
        return 200 /path/to/file;
    }
}

不一定必须 if 中实现, 只要是在满足变量$var=true 的情况下, 返回指定路径静态文件内容即可

2855 次点击
所在节点    NGINX
4 条回复
yeept
2020-08-25 08:22:33 +08:00
proxy_pass 可以实现?
ijaysdev
2020-08-25 08:57:38 +08:00
帮顶
thinkmore
2020-08-28 18:14:19 +08:00
```nginx
location /condition {
# 条件满足
rewrite /condition(.*) /first last;
}

location /first {
root html;
index 200 1.txt;
}

```

当访问 http://localhost/condition 的时候实际访问的是 fist 下的内容。

所以你可以按照这个思路,当某种条件满足的时候就将 url rewrite

@GGGG430
abccccabc
2021-03-24 09:44:33 +08:00
return 200 /path/to/file;

这个返回 200 的同时,并不是返回的文件内容,而是一个 “/path/to/file”字符串

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/701036

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX