Nginx正向代理,解决跨域问题

2020-03-25  本文已影响0人  笙笙哥

PS: 解决客户端跨域问题,非服务器端配置

1. 安装

sudo brew install nginx

2. 启动

//方式一
sudo nginx  
//方式二
sudo brew services start nginx

解决跨域问题

原理:通过合并两个网站到同一个主机(通过路径区分主机),来避免跨域问题

找到配置文件

/usr/local/etc/nginx/nginx.conf

修改http下面的server节点


    server {
        listen       8090; //本地访问的端口
        server_name  localhost; //本地访问的地址

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {//服务器一,通过 http://localhost:8090/
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

            proxy_set_header X-real-ip $remote_addr;

            proxy_pass http://localhost:8080;
        }

        location /api/ { //服务器二,通过 http://localhost:8090/api/访问,api可以改成自定义路劲
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

            proxy_set_header X-real-ip $remote_addr;
            
            rewrite ^/api/(.*)$ /$1 break; 
            proxy_pass http://apptest.xxx.net;  
        }
}

重启 nginx

sudo nginx -s reload

说明

http://localhost:8090/  //服务器一
http://localhost:8090/api/  //服务器二,可用于程序里调用api的地址,一次类推多台服务器一样的配置

可能遇到的问题:
报错:
nginx: [alert] kill(2783, 1) failed (3: No such process)
原因:未启动,所以重新启动即可

解决:

sudo nginx 

nginx 常用命令

nginx -s reload 重新加载配置
nginx -s reopen 重启
nginx -s stop 停止
nginx -s quit 退出
nginx -V 查看版本,以及配置文件地址
nginx -v 查看版本
nginx -c filename 指定配置文件
nginx -h 帮助
上一篇 下一篇

猜你喜欢

热点阅读