小满Linux(第八章Nginx反向代理)

nginx news

Nginx反向代理的配置语法

反向代理中的常用指令:

proxy_pass 
proxy_set_header 

proxy_pass

该指令用来设置被代理服务器地址,可以是主机名称、IP地址加端口号形式。

案例1代理到哔哩哔哩

location / {
   root   html;
   index  index.html index.htm;
   proxy_pass http://bilibili.com;
}

访问/就会被转到哔哩哔哩

案例2 nginx反向代理解决跨域

前端代码

         a.onclick = () => {
            let xhr = new XMLHttpRequest()

            xhr.open('GET','/api/portal/list')

            xhr.onreadystatechange = () => {
                if(xhr.readyState == 4 &&  xhr.status == 200){
                   console.log(xhr.responseText);
                }
            }

            xhr.send(null)
         }

express 服务端代码

const express = require('express')

const app = express()


app.get('/portal/list', (req, res) => {
    res.json({
        code: 200,
        message: "搞咩啊"
    })
})

app.listen(9000,()=>{
    console.log('success');
})

nginx 配置文件

        location /api/ {
            proxy_pass http://localhost:9000/;
        }

截取到/api/ 将会转发到 http://localhost:9000/

proxy_set_header

该指令可以更改Nginx服务器接收到的客户端请求的请求头信息,然后将新的请求头发送给代理的服务器

proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Real-Port $remote_port;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
三个header分别表示:
X-Real-IP 客户端或上一级代理ip
X-Real-Port 客户端或上一级端口
X-Forwarded-For 包含了客户端和各级代理ip的完整ip链路
其中X-Real-IP是必需的,后两项选填。当只存在一级nginx代理的时候X-Real-IP和X-Forwarded-For是一致的,而当存在多级代理的时候,X-Forwarded-For 就变成了如下形式 

$remote_addr是前一节点的IP,并不一定是用户的真实IP。

猜你喜欢

转载自blog.csdn.net/qq1195566313/article/details/124486764