摘要生成中...
AI 摘要
Hunyuan-lite

精通 Nginx,学其它的 Apache、Tomcat 更轻松。

安装 Nginx

CentOS 中通过 DNF 包管理器自动下载安装

本案例中使用的服务器信息

CPU&内存:1 核 (vCPU)2 GiB
操作系统:Alibaba Cloud Linux 3.2104 64 位
实例规格:ecs.n4.small
实例规格族:共享计算型
刚刚初始化云盘的 ECS 服务器。

运行以下命令安装 Nginx:

1
dnf -y install http://nginx.org/packages/centos/8/x86_64/RPMS/nginx-1.22.1-1.el8.ngx.x86_64.rpm 

您可以访问 Nginx官方安装包 获取适用于 CentOS 8 系统的多版本的 Nginx 安装包。

通过官网下载源代码自行编译

最原始的方式

官网软件包下载地址:nginx: download

1
curl -o nginx-1.20.2.tar.gz https://nginx.org/download/nginx-1.20.2.tar.gz

解压:

1
2
tar -zxvf nginx-1.20.2.tar.gz
cd nginx-1.20.2

检查依赖:

1
./configure

yum 安装缺失的库:

1
2
yum install pcre pcre-devel -y
yum install openssl openssl-devel -y

安装完毕后可再次进行依赖检查 ./configure

设置系统参数:

1
./configure --with-http_ssl_module --with-http_v2_module --with-stream

编译与安装:

1
2
make
make install

编译出来的二进制文件在 /usr/local/nginx/sbin/nginx 中(之前 configure 检查时有提示)。

接下来配置环境变量,将二进制文件的地址配置进去:

1
vim /etc/profile

在打开的文件中的最后加入以下内容:

1
export PATH=$PATH:/usr/local/nginx/sbin

刷新使配置文件生效:

1
source /etc/profile

验证并启动 Nginx

运行以下命令查看 Nginx 版本。

1
nginx -v

启动 Nginx 服务:

1
systemctl start nginx

在本地电脑的浏览器输入主机地址并访问,出现 Nginx 默认页面即成功。

image-20230409141117412

反向代理的配置

一般的请求转发

找到 nginx.conf 文件进行配置,一般在 /etc/nginx 目录下。但我遇到一个问题,就是配置文件没有 server 字段。于是我参考了 这篇文章。最终在 /etc/nginx/conf.d/default.conf 中找到了。

修改配置文件,设定好网站的根目录:

image-20230408205637757

重启 Nginx:

1
2
3
systemctl restart nginx
# 或 nginx -s reload # 不用重启nginx
# 或 systemctl reload nginx

你可以在服务器上对应自己设置的根目录创建文本文件,如 xiazai.txt,然后浏览器访问网址 <服务器主机IP>/xiazai.txt 进行测试。

SSE 请求转发

如果服务器部署的服务需要通过 SSE 协议交流(MCP Server),那么注意 Nginx 中不要破坏掉 SSE 的传输过程。一份能正确运行的配置如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
server {
listen 443 ssl;
server_name mcp.uuanqin.top; # 你的域名,确保已解析到服务器 IP

location / {
proxy_pass http://localhost:8991;
proxy_http_version 1.1; # 必须用 HTTP/1.1
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;
# MCP 协议专用转发配置(关键!)
proxy_set_header Connection ""; # 禁用连接重置,保持长连接
proxy_buffering off; # 禁用缓冲,保证帧传输完整
proxy_cache off; # 禁用缓存
proxy_read_timeout 120s; # 延长读超时(MCP 握手需要时间)
proxy_send_timeout 120s;
}

# 可选:添加访问日志,方便排查问题
access_log /var/log/nginx/mcp.uuanqin.top.access.log main;
error_log /var/log/nginx/mcp.uuanqin.top.error.log;

ssl_certificate /etc/letsencrypt/live/mcp.uuanqin.top/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/mcp.uuanqin.top/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
if ($host = mcp.uuanqin.top) {
return 301 https://$host$request_uri;
} # managed by Certbot

listen 80;
server_name mcp.uuanqin.top;
return 404; # managed by Certbot
}

本文参考