配置Nginx解决跨域问题

Nginx 中将前端请求中的所有以 "/apiUrl" 开头的路径代理到 http://192.12.200.101:9813

例如:

/apiUrl/login ===> http://192.12.200.101:9813/login

配置nginx环境

  • 进入Nginx 的配置文件编辑界面:
python 复制代码
sudo nano /etc/nginx/conf.d/default.conf
  • 开始编辑 default.conf
bash 复制代码
server {
    listen       80;
    server_name  localhost;
    # 这里配置,配置如下
    location /apiUrl/ {
        rewrite ^/apiUrl(/.*)$ $1 break; # 路径重写
        proxy_pass http://192.12.200.101:9813; # 代理请求转发的目标地址
        add_header Access-Control-Allow-Origin *; # 表示允许任何域的请求访问资源。
        add_header Access-Control-Allow-Methods *;# 定义允许跨域请求的 HTTP 方法
        proxy_set_header Content-Type "application/x-www-form-urlencoded; charset=UTF-8"; # 设置代理请求时的 HTTP 请求头部信息。
     }

    #charset koi8-r;
    access_log  /var/log/nginx/host.access.log  main;
    error_log  /var/log/nginx/error.log  error;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

纯净版:这里复制

bash 复制代码
location /apiUrl/ {
        rewrite ^/apiUrl(/.*)$ $1 break;
        proxy_pass http://192.12.200.101:9813;
        add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Allow-Methods *;
        proxy_set_header Content-Type "application/x-www-form-urlencoded; charset=UTF-8";
     }
  • 重启nginx
bash 复制代码
sudo service nginx restart

注意:

如果想/apiUrl/login ===> http://192.12.200.101:9813/apiUrl/login

这里路径匹配规则 /apiUrl/,如下图:

/apiUrl ----匹配到的路径----> /apiUrl,/apiUrl1,/apiUrl2

/apiUrl/ ----匹配到的路径--只有 /apiUrl

允许多个信任域名进行跨域访问,你可以在 Access-Control-Allow-Origin 头部中设置多个域名:
多个域名时:双引号或单引号内,使用逗号隔开;

bash 复制代码
add_header Access-Control-Allow-Origin "https://your-allowed-domain-1.com, https://your-allowed-domain-2.com, https://your-allowed-domain-3.com";

自定义允许跨域请求的 HTTP 方法:

bash 复制代码
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS, DELETE';

nginx官方文档--rewrite

相关推荐
虎头金猫2 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
还是大剑师兰特2 天前
解决nginx错误:http://localhost:7000正常,http://localhost:7000/map 报错404
nginx·大剑师
AI职业加油站2 天前
AI智能体应用工程师证书:政策红利下的职业新风口
大数据·运维·人工智能·学习·职场发展
此冬歌咏2 天前
K8s 节点故障实战:优雅驱逐 31 秒,硬故障 331 秒,以及那个永远 Pending 的 Pod
运维·k8s
xing-xing2 天前
Docker容器中Nginx站点根目录网页配置访问
nginx·docker
-梅2 天前
linux(8) 软硬链接
linux·运维·服务器
张洛闻Eren2 天前
k8s云原生【第十课】:水平 Pod 自动扩缩容
运维·数据库·云原生·kubernetes·github
其实防守也摸鱼3 天前
内网穿透与反向代理:原理、工具与实战指南
android·大数据·运维·安全·网络安全·自动化·渗透
布裘3 天前
【银河麒麟】V4桌面图标消失,右击鼠标没反应排查
运维·银河麒麟·桌面环境
懂软件的胡子个哥3 天前
微信机器人为什么需要“回复候选”而不是所有 AI 内容直接发送
运维·微信·自动化·wechatapi·个人微信号二次开发