nginx 反向代理实操
下面是一个使用 Nginx 配置反向代理的示例:
假设我们有一个 backend 服务器运行在 http://localhost:8080,我们想通过反向代理在 http://example.com 访问它。
我们可以在 Nginx 配置文件中添加以下配置:
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://localhost:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
这里的每一行都做了什么:
listen 80; - 监听端口 80(默认的 HTTP 端口)
server_name example.com; - 设置服务器名称为 example.com
location / {… } - 定义一个根 URL (/) 的位置块
proxy_pass http://localhost:8080; - 将请求代理到 http://localhost:8080
proxy_http_version 1.1; - 设置 HTTP 版本为 1.1
proxy_set_header Upgrade $http_upgrade; - 设置 Upgrade 头部为原始请求的 Upgrade 头部值
proxy_set_header Connection ‘upgrade’; - 设置 Connection 头部为 upgrade
proxy_set_header Host $host; - 设置 Host 头部为原始请求的 Host 头部值
proxy_cache_bypass $http_upgrade; - 为 WebSocket 连接绕过缓存
添加了这个配置后,重新启动 Nginx 以应用更改:
sudo service nginx restart