V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
NGINX
NGINX Trac
3rd Party Modules
Security Advisories
CHANGES
OpenResty
ngx_lua
Tengine
在线学习资源
NGINX 开发从入门到精通
NGINX Modules
ngx_echo
GGGG430
V2EX  ›  NGINX

nginx 返回静态文件配置问题

  •  
  •   GGGG430 · 2020-08-24 18:05:49 +08:00 · 2808 次点击
    这是一个创建于 1313 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    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 的情况下, 返回指定路径静态文件内容即可

    4 条回复    2021-03-24 09:44:33 +08:00
    yeept
        1
    yeept  
       2020-08-25 08:22:33 +08:00
    proxy_pass 可以实现?
    ijaysdev
        2
    ijaysdev  
       2020-08-25 08:57:38 +08:00
    帮顶
    thinkmore
        3
    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
        4
    abccccabc  
       2021-03-24 09:44:33 +08:00
    return 200 /path/to/file;

    这个返回 200 的同时,并不是返回的文件内容,而是一个 “/path/to/file”字符串
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2732 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 12:42 · PVG 20:42 · LAX 05:42 · JFK 08:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.