二十九、Nginx添加判断实现自动跨域

自动跨域

支持添加到location层;
nginx自动判断是否添加跨域:如果前/后端代码添加了跨域配置nginx则不处理,否则nginx将添加跨域配置
生效配置:nginx -s reload

配置跨域

请确保将此配置放置在Nginx配置文件的适当位置,通常是匹配所需端点的location块内。

server {
    listen 80;
    listen 443 ssl;
    server_name xxx.com;
    charset utf-8;
    root html;
    index index.html index.htm;
    
    location / {
        proxy_pass http://xxx;
        ################################ 自动跨域 ################################
        if ($request_method = 'OPTIONS') {
            # 允许请求的来源(所有)
            add_header 'Access-Control-Allow-Origin' '*';
            # 允许的跨域请求方法
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';

            ############## 此配置是可选的 ##############
 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要在nginx上配置node.js跨域,可以使用nginx的反向代理功能。以下是一个示例配置: ```nginx server { listen 80; # 配置允许跨域请求的域名 add_header 'Access-Control-Allow-Origin' 'http://yourdomain.com'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Headers' 'DNT,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; location / { # 配置反向代理到node.js服务器的地址和端口 proxy_pass http://127.0.0.1:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # 配置允许WebSocket跨域请求 proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } } ``` 上述配置会在nginx服务器上监听80端口,将所有请求代理到node.js服务器的3000端口,并添加允许跨域请求的header信息。其中`Access-Control-Allow-Origin`配置了允许跨域请求的域名,`Access-Control-Allow-Methods`配置了允许的请求方法,`Access-Control-Allow-Credentials`配置了是否允许发送cookie等凭证信息,`Access-Control-Allow-Headers`配置了允许的请求头信息。此外,还配置了允许WebSocket跨域请求的相关信息。 你可以将以上配置保存为一个nginx配置文件,然后使用`nginx -c /path/to/nginx.conf`命令启动nginx服务器
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秋风お亦冷

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值