NGINX
NGINX Trac
3rd Party Modules
Security Advisories
CHANGES
OpenResty
ngx_lua
Tengine
在线学习资源
NGINX 开发从入门到精通
NGINX Modules
ngx_echo
GGGG430
V2EX  ›  NGINX

nginx 返回静态文件配置问题

  •  
  •   GGGG430 · Aug 24, 2020 · 4110 views
    This topic created in 2122 days ago, the information mentioned may be changed or developed.

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

    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 replies    2021-03-24 09:44:33 +08:00
    yeept
        1
    yeept  
       Aug 25, 2020
    proxy_pass 可以实现?
    ijaysdev
        2
    ijaysdev  
       Aug 25, 2020
    帮顶
    thinkmore
        3
    thinkmore  
       Aug 28, 2020
    ```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  
       Mar 24, 2021
    return 200 /path/to/file;

    这个返回 200 的同时,并不是返回的文件内容,而是一个 “/path/to/file”字符串
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5408 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 74ms · UTC 05:58 · PVG 13:58 · LAX 22:58 · JFK 01:58
    ♥ Do have faith in what you're doing.