nginx配置文件服务器及反向代理

发布时间 2023-11-28 15:20:45作者: 汗牛充栋

nginx 配置文件服务器及反向代理

最终配置如下:

worker_processes  1;
events {
    worker_connections  1024;
}

http{
    server {
        listen      8888;
        add_header 'Access-Control-Allow-Origin' '*';
        server_name  example.com;

        location / {
            return 404;
        }

        location /file/ {
            alias   D:/xxx/xxx/;
            allow all;
            autoindex on;
            charset utf-8;
        }

        location /logs/ {
            alias   C:/xxx/xxx/;
            allow all;
            autoindex on;
            charset utf-8;
        }

        location /api/test1/ {
            proxy_connect_timeout 10s;
            proxy_read_timeout 1800s;

            proxy_pass http://localhost:10024;
            proxy_set_header Host $host:$server_port;
        }
    }
}

搭建文件服务器

其中下面的配置即是提供文件服务的:

location /file/ {
	alias   D:/xxx/xxx/;
	allow all;
	autoindex on;
	charset utf-8;
}

location /logs/ {
	alias   C:/xxx/xxx/;
	allow all;
	autoindex on;
	charset utf-8;
}

可以通过访问部署nginx服务器的ip加上8888端口, 加载uri:/file/或者/logs/即可访问文件目录进行下载。假如nginx所在服务器ip为192.168.0.1, 那么就是访问地址: http://192.168.0.1:8888/file/ 或者 http://192.168.0.1:8888/logs/ 即可访问到对应目录下的文件。
其中指定 autoindex用于显示目录, charset指定字符编码, 否则下载文本文件可能乱码。

跨域问题

跨域的配置主要是这一句:

add_header 'Access-Control-Allow-Origin' '*';

反向代理

首先, 什么是反向代理?反向代理其实是相对正向代理而言的,那正向代理是什么呢?
正向代理打个比方就是,我们要访问google.com, 但是无法直接访问,但某个代理服务器A是可以访问到google.com, 而我们又可以访问到代理服务器A, 那么此时代理服务器A即是充当代理服务器的角色。
那反向代理呢?反向代理就好比我们访问baidu.com, 但是baidu.com所指示的服务是一个代理服务器, 具体做事的可能是其某个内部节点, 可能是多个节点。

配置反向代理关键配置如下:

location /api/test1/ {
	proxy_connect_timeout 10s;
	proxy_read_timeout 1800s;

	proxy_pass http://localhost:10024;
	proxy_set_header Host $host:$server_port;
}
  • proxy_connect_timeout 设置代理服务器与后端服务器建立连接的超时时间,单位为秒
  • proxy_read_timeout 设置代理服务器从后端服务器读取数据的超时时间,单位为秒
  • proxy_send_timeout 设置代理服务器向后端服务器发送数据的超时时间,单位为秒
  • proxy_pass 指定了实际被代理的服务器地址
  • proxy_set_header 用于重新定义或者添加发往后端服务器的请求头, 示例中是重新设置了header中的Host字段。

其他超时设置

  • client_body_timeout 设置客户端向服务器发送请求体的超时时间,单位为秒
  • client_header_timeout 设置客户端向服务器发送请求头的超时时间,单位为秒
  • send_timeout 设置服务器向客户端发送响应的超时时间,单位为秒
  • keepalive_timeout 设置服务器与客户端之间保持连接的超时时间,单位为秒