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

相关推荐
华纳云IDC服务商2 小时前
服务器Linux防火墙怎样实现访问控制
linux·运维·服务器
胡桃不是夹子3 小时前
linux系统装google chrome,amd64
linux·运维·chrome
睡觉z8 小时前
Jenkins持续集成系统
运维·ci/cd·jenkins
Wy_编程11 小时前
Linux文件相关命令
linux·运维
Viking_bird11 小时前
centos 7.5 + Hadoop 3.2.4 集群搭建
linux·运维·服务器·hadoop·centos
黑客影儿13 小时前
Kali Linux 环境中的系统配置文件与用户配置文件大全
linux·运维·程序人生·安全·网络安全·系统安全·学习方法
岚天start13 小时前
Linux系统网络排查工具总结
linux·运维·网络·监控·扫描·连通性·流量
Lovyk14 小时前
基于 Ansible 与 Jinja2 模板的 LNMP 环境及 WordPress 自动化部署实践
linux·运维·服务器·自动化·ansible
知白守黑26715 小时前
Linux磁盘阵列
linux·运维·服务器
维尔切16 小时前
Linux中基于Centos7使用lamp架构搭建个人论坛(wordpress)
linux·运维·架构