跨域问题解决方式之反向代理

以下是使用 Nginx 配置反向代理的具体操作步骤:

安装 Nginx

在大多数 Linux 发行版中,可以通过以下命令安装 Nginx:

1
2
sudo apt update
sudo apt install nginx

安装完成后,访问服务器的 IP 地址(如 http://your-server-ip),在浏览器中查看默认的 Nginx 欢迎页面,确认安装成功。

编辑 Nginx 配置文件

Nginx 的主要配置文件通常位于 /etc/nginx/nginx.conf,也可以在 /etc/nginx/sites-available 目录下创建单独的站点配置文件。

以下是一个基本的反向代理配置示例:

1
2
3
4
5
6
7
8
9
10
11
12
server {
listen 80;
server_name example.com;

location / {
proxy_pass http://backend-server-ip:port;
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;
}
}
  • proxy_pass 指定后端服务的地址。
  • proxy_set_header 设置转发的请求头,用于保留客户端的真实 IP。

测试并重启 Nginx

保存配置后,运行以下命令测试配置语法:

1
sudo nginx -t

如果测试通过,重启 Nginx 应用配置:

1
sudo systemctl restart nginx

验证反向代理

完成配置后,通过浏览器访问 http://example.com,验证反向代理是否工作正常。如果配置正确,应能看到后端服务的内容。

注意事项

  • 如果后端服务使用 HTTPS,proxy_pass 需要改为 https://
  • 如果需要代理特定路径,可以在 location 中指定路径,如 location /api/
  • 确保后端服务的防火墙允许来自代理服务器的访问。

通过以上步骤,你可以使用 Nginx 配置反向代理,实现跨域请求的转发。