
本文将演示如何在CentOS 7.5系统上搭建基于Nginx的TCP反向代理。
一、系统更新与Nginx安装
首先,更新系统软件包:
<code class="bash">$ yum -y update</code>
然后,安装Nginx:
<code class="bash"># 添加Nginx软件源 (参考 http://nginx.org/en/linux_packages.html#stable) $ vi /etc/yum.repos.d/nginx.repo [nginx] name=nginx repo baseurl=http://nginx.org/packages/centos/7/$basearch/ gpgcheck=0 enabled=1 $ yum -y install nginx</code>
验证安装:
<code class="bash">$ nginx -V</code>
二、Nginx配置
修改主配置文件 /etc/nginx/nginx.conf:
<code class="nginx">user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
stream {
log_format proxy '$remote_addr [$time_local] $protocol $status $bytes_sent $bytes_received $session_time "$upstream_addr" "$upstream_bytes_sent" "$upstream_bytes_received" "$upstream_connect_time"';
access_log /var/log/nginx/tcp-access.log proxy;
open_log_file_cache off;
include /etc/nginx/conf.d/*.stream;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
# 关闭版本显示
server_tokens off;
# gzip 压缩传输
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.0;
gzip_comp_level 2;
gzip_types text/plain application/x-javascript text/css application/xml;
gzip_vary on;
# 配置代理参数
proxy_redirect off;
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_connect_timeout 90;
proxy_read_timeout 90;
proxy_send_timeout 90;
proxy_buffer_size 4k;
# 缓存配置
proxy_temp_file_write_size 264k;
proxy_temp_path /var/cache/nginx/nginx_temp;
proxy_cache_path /var/cache/nginx/nginx_cache levels=1:2 keys_zone=cache_one:200m inactive=5d max_size=400m;
proxy_ignore_headers X-Accel-Expires Expires Cache-Control Set-Cookie;
include /etc/nginx/conf.d/*.conf;
}</code>(请根据实际情况修改配置文件,例如添加具体的upstream配置) 此配置示例包含了HTTP和Stream模块的配置,以及一些性能优化选项,例如gzip压缩和缓存。 你需要根据你的具体需求,在 /etc/nginx/conf.d/ 目录下创建相应的配置文件来定义upstream服务器和反向代理规则。
三、重启Nginx
完成配置修改后,重启Nginx使配置生效:
<code class="bash">$ systemctl restart nginx</code>
通过以上步骤,你就可以在CentOS 7.5上搭建一个基于Nginx的TCP反向代理。 记住,你需要根据你的具体应用场景配置相应的upstream服务器和反向代理规则。
以上就是干货:基于nginx的tcp反向代理案例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号