配置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

相关推荐
RisunJan8 分钟前
Linux命令-nohup(使进程忽略挂起(HUP)信号并在后台继续运行)
linux·运维·服务器
STDD25 分钟前
VictoriaLogs:轻量级日志存储方案,Loki 的高效替代
运维·jenkins
枳实-叶33 分钟前
【Linux驱动开发】第18天:I2C驱动深度解析
linux·运维·驱动开发
shandianchengzi37 分钟前
【记录】Ubuntu|Ubuntu 26.04 笔记本耗电过快,排查 省电过程
linux·运维·ubuntu
一叶星殇41 分钟前
日志成海,何以检索:Serilog 解锁 .NET 日志可查询新范式
运维·服务器
企服AI产品测评局42 分钟前
AI Agent实测:Agent Store现成应用如何重塑企业自动化?
运维·人工智能·ai·chatgpt·自动化
上海云盾安全满满44 分钟前
服务器不稳定,丢包有哪些原因?
运维·服务器
陳10301 小时前
Linux:信号
linux·运维·服务器
tongluowan0071 小时前
负载均衡之硬件与软件层面的异同
运维·nginx·负载均衡·f5
小此方1 小时前
Re:Linux系统篇(二十五)进程篇·十:深度硬核!Linux 进程等待,从 task_struct 源码到位图状态解构
linux·运维·驱动开发