Nginx 典型安装与反向代理配置实践:支持 HTTP、HTTPS、WebSocket、TCP 协议
在实际业务部署中,Nginx 作为一款轻量级、高性能且稳定的反向代理和负载均衡工具,被广泛应用于微服务架构、前后端分离系统、API 网关以及静态资源服务等多种场景。
本文将详细介绍 Nginx 的典型安装及配置方法,重点涵盖 HTTP、HTTPS、WebSocket 以及 TCP 协议的反向代理实践。文中附有完整且可直接使用的配置示例,并配以详尽的参数说明,帮助你快速上手。
下一篇文章,我将分享如何基于 Keepalived 实现 Nginx 的高可用方案,敬请关注。
一、Nginx 安装方式(建议源码编译开启所有模块)
推荐方式:源码安装(支持 TCP、WebSocket、HTTPS)
# 安装基础依赖
sudo yum install -y gcc pcre pcre-devel zlib zlib-devel openssl openssl-devel
# 下载 Nginx 源码
wget http://nginx.org/download/nginx-1.29.0.tar.gz
tar -zxvf nginx-1.29.0.tar.gz && cd nginx-1.29.0
# 编译启用 Stream(TCP)、SSL、WebSocket 所需模块
./configure --prefix=/usr/local/nginx \
--with-http_ssl_module \
--with-stream \
--with-http_v2_module
make && sudo make install
✅ 默认配置文件路径:
/usr/local/nginx/conf/nginx.conf
✅ 启动 Nginx:/usr/local/nginx/sbin/nginx
文章最后我提供一份 systemd 管理方式启动 services 文件。
✅ 测试配置语法:/usr/local/nginx/sbin/nginx -t
二、HTTP 反向代理配置示例
http {
upstream backend_http {
server 127.0.0.1:8080;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend_http;
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_pass
:设置要转发的目标地址proxy_set_header
:设置转发请求头,保留用户真实 IP 等信息upstream
:定义后端服务池,可添加多个 IP 做负载均衡
三、HTTPS 反向代理配置示例
http {
upstream backend_http {
server 127.0.0.1:8080;
}
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/nginx/ssl/example.crt;
ssl_certificate_key /etc/nginx/ssl/example.key;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
location ^~ /queryuser {
# 处理 CORS 预检请求(OPTIONS)
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' $http_origin always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET,POST,PUT,DELETE,PATCH,OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Content-Type,ssid';
add_header 'Content-Length' 0;
add_header 'Content-Type' text/plain;
return 204;
}
# 正常请求代理
proxy_pass http://backend_http;
proxy_set_header Host $host;
proxy_redirect off;
# 跨域响应头
add_header 'Access-Control-Allow-Origin' $http_origin always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET,POST,PUT,DELETE,PATCH,OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Content-Type,ssid';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Type' always;
add_header 'Vary' 'Origin' always;
}
}
}
💡 参数说明:
ssl_certificate
/ ssl_certificate_key
:指定 SSL 证书及私钥路径,用于启用 HTTPS。
ssl_prefer_server_ciphers on
:优先使用服务器定义的加密套件,增强安全性。
ssl_session_cache
:开启 SSL 会话缓存,提高性能。
ssl_session_timeout
:定义会话缓存超时时间,单位为分钟。
Access-Control-Allow-Origin $http_origin
:动态允许来源请求中的域名(不能使用 *
和 credentials: true
同时存在)。
Access-Control-Allow-Credentials 'true'
:允许浏览器携带 Cookie 等认证信息。
Access-Control-Allow-Methods
:允许的 HTTP 方法列表。
Access-Control-Allow-Headers
:允许客户端请求中携带的自定义头部(如 Content-Type
、ssid
等)。
Access-Control-Expose-Headers
:允许客户端 JS 访问的响应头字段。
Vary 'Origin'
:提示浏览器或 CDN,缓存应根据 Origin 变化分别处理。
proxy_pass
:将请求转发至后端服务(本例为 127.0.0.1:8080)。
proxy_set_header Host $host
:将原始 Host 头传递给后端,保持主机信息一致。
proxy_redirect off
:关闭默认的重定向行为,防止干扰代理响应地址。
四、WebSocket 代理配置示例
WebSocket 使用 HTTP 协议升级(Upgrade)机制,必须设置相关头信息,才能正确代理。
http {
upstream websocket_backend {
server 127.0.0.1:7000;
}
server {
listen 443 ssl;
server_name ws.example.com;
ssl_certificate /etc/nginx/ssl/ws.example.com.crt;
ssl_certificate_key /etc/nginx/ssl/ws.example.com.key;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
location ^~ /ws {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' $http_origin always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET,POST,PUT,DELETE,PATCH,OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Content-Type,ssid';
add_header 'Content-Length' 0;
add_header 'Content-Type' text/plain;
return 204;
}
proxy_pass http://websocket_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
add_header 'Access-Control-Allow-Origin' $http_origin always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET,POST,PUT,DELETE,PATCH,OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Content-Type,ssid';
add_header 'Vary' 'Origin' always;
}
}
}
参数说明:
proxy_http_version 1.1
:WebSocket 需要使用 HTTP/1.1Upgrade
/Connection
头:用于建立持久连接/ws
:可自定义 WebSocket 路由前缀
五、TCP 反向代理配置示例(需开启 --with-stream
模块)
# 注意:stream 块与 http 块并列,不能嵌套
stream {
upstream mysql_cluster {
server 127.0.0.1:3306;
}
server {
listen 3307;
proxy_pass mysql_cluster;
}
}
📌 使用场景:
适合代理非 HTTP 协议的服务,例如:
- MySQL
- Redis
- RabbitMQ
- Kafka
⚠️ 需确保编译时启用了
--with-stream
,否则会报错unknown directive "stream"
六、访问本地静态文件示例
http {
server {
listen 80;
server_name static.example.com;
location / {
root /usr/local/nginx/html;
index index.html index.htm;
}
}
}
将静态文件(如 HTML/CSS/JS)放入 /usr/local/nginx/html
目录后,即可通过 http://static.example.com/index.html
访问。
👉 示例:
echo "<h1>Hello Nginx</h1>" > /usr/local/nginx/html/index.html
访问地址:http://<服务器IP>/
七:Services配置
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t -c /etc/nginx/nginx.conf
ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
👉 说明
- [Unit]:描述服务及依赖,
After=network.target
表示网络启动后启动 Nginx。 - [Service]:
Type=forking
表示服务是通过 fork 子进程启动的。PIDFile
指定 pid 文件位置。ExecStartPre
启动前测试配置文件正确性。ExecStart
启动命令。ExecReload
重新加载配置。ExecStop
停止命令。PrivateTmp=true
为服务提供私有的 /tmp。
- [Install]:
WantedBy=multi-user.target
表示在系统多用户模式下启动。
八、总结与建议
- 推荐使用
upstream
管理后端服务,便于扩展; - 配置中应注意:路径末尾的
/
影响代理行为; - 使用
proxy_set_header
保留原始请求信息是必要的安全与日志手段。
👉 更多建议
- 开启 Gzip 支持提升前端加载速度;
- 日志拆分配置便于排查问题;
- 结合 Fail2Ban 做访问安全防护;
- 后续可引入
OpenResty
进行 Lua 动态逻辑扩展。
🔍 本文旨在提供 Nginx 配置实用模板与部署指引,更多进阶内容(如热重载、负载策略、限流防刷等)将在后续推送中发布。
重点提醒 :喜欢请加关注哦 !
📣 更多原创内容、技术干货,欢迎关注微信公众号 「键上江湖」,与你一键相逢!