Nginx 反向代理

2025/02/25 Nginx 共 955 字,约 3 分钟

主要有http反向代理和TCP反向代理

主配置, 对应两个部分

# nginx.conf

user www-data;
worker_processes auto;
pid /run/nginx.pid;
error_log /var/log/nginx/error.log;

include /etc/nginx/modules-enabled/*.conf;

events {
	worker_connections 768;
	# multi_accept on;
}

# TCP反向代理设置
include /etc/nginx/stream.d/*.conf;

http {

	# http 反向代理设置模块
	include /etc/nginx/conf.d/*.conf;
	include /etc/nginx/sites-enabled/*;
}

http反向代理 conf.d 目录下

xxxx.conf

server {
    listen 32235;
    server_name _;

    # 转发请求到服务器 B 的 192.168.100.214:22235
    location / {
        proxy_pass http://192.168.100.214:22235;

        # 保留原始请求头
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        # 禁止访问 nginx 的隐藏文件
        location ~ /\. {
            deny all;
        }
    }

    # 日志配置
    access_log /var/log/nginx/service_access.log;
}

TCP反向代理,比如22端口, stream.d目录下

  1. 安装stream模块,最简单的方式
    sudo apt install nginx-full
    
  2. ssh服务端口配置示例
stream {
    server {
        listen 2222;
        proxy_pass 192.168.100.214:22;

        # 等待后端响应的最大时间为 10 分钟
        proxy_timeout 10m;

        # 与后端建立连接的最大等待时间为 1 秒
        proxy_connect_timeout 1s;
    }
}

文档信息

Search

    Table of Contents