Nginx在反向代理连接失败时回退到本地文件的配置

需求:用户连接时,默认显示反向代理的内容,如果后端服务器无法连接,则显示预先渲染好的本地文件。

实现:

server {
    # ... #

    # define a named location block for static files
    location @local_static_files {
        root /var/www/html;
        index index.html;
        try_files $uri $uri/index.html =404;
        break;
    }

    location / {
        # try proxy first
        proxy_pass http://backend-server:8080/;
        
        # set a relative smaller timeout to minimize user wait time
        client_max_body_size    16m;
        client_body_buffer_size 128k;
        proxy_connect_timeout   2s;
        proxy_send_timeout      1s;
        proxy_read_timeout      1s;
        proxy_buffers           32 4k;

        # see https://github.com/Jamesits/oh-my-nginx/blob/master/conf.d/templates/transparent-proxy.conf
        include conf.d/templates/transparent-proxy.conf;

        # if the backend is down (502), we fallback to our local static files
        error_page 502 = @local_static_files;

        # if you need to mask more proxy failures: 
        # proxy_intercept_errors on; # intercept all >300 return code if you need
    }

    # ... #
}

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据