Nginx反向代理
nginx反向代理在http块下面的server块中的location块内进行配置:
反向代理中常用的指令:
proxy_pass
proxy_set_header
proxy_pass
proxy_pass指令用来设置目标服务器地址,可以是主机名称、IP地址加端口号的形式。
案例1:代理到bilibili
实现效果:在浏览器地址栏中输入服务器的地址,然后跳转到bilibili首页。
首先我们先找到nginx.conf所在的位置:
whereis nginx
cd /usr/local/nginx
ls
cd conf
ls
vim nginx.conf
然后在nginx.confnginx配置文件中配置代理规则:
location / {
proxy_pass http://www.bilibili.com
}
当我们nginx的server_name+location后边的路径时,nginx会将proxy_pass后边的路径与location后边的路径拼接起来然后进行访问,类似上面的配置将会是这样的:http://www.bilibili.com,/可以省略。
然后我们输入服务器的IP地址(域名):端口/bilibili进行访问:
前面有一个 # 的蓝色部分为注释。
可以看到我们已经成功的使用nginx进行转发请求了。
案例2
实现效果:浏览器具有同源策略,这个策略导致浏览器在访问一个协议、域名、端口号中任意一个不一样的地址时,会出现跨域。使用nginx进行反向代理,成功请求到node接口。
这个是部署到服务器上的接口:
node接口:
const express = require('express')
const app = express()
app.get('/api/test', (req, res) => {
console.log(req.ip)
res.send({
code: 200,
message: '访问成功!'
})
})
app.listen(8888, () => {
console.log('服务成功运行!')
})
本地:
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>发送</button>
<script>
window.addEventListener('DOMContentLoaded', function () {
const btn = document.querySelector('button')
btn.addEventListener('click', function () {
const xhr = new XMLHttpRequest()
xhr.open('GET', 'http://101.200.242.117:8888/api/test')
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.response);
}
}
xhr.send()
})
})
</script>
</body>
</html>
如果说我们直接open in default browser在浏览器中打开网页,直接去请求这个接口,浏览器会给我们报错跨域问题:
解决跨域问题
-
将
index.html放到nginx/html下 为了解决这个问题,首先我们把这个index.html文件放到nginx/html目录下:nginx.conf的默认配置:location / { root html index index.html index.htm }当我们访问
localhost的时候,它会去访问nginx/html目录下的index.html。 -
在
nginx.conf中添加如下:http { server { server_name 127.0.0.1; location /api { proxy_pass http://127.0.0.1:8888; } } } -
重载
nginx.confnginx - s reload -
启动
nginxnginx -
访问
localhost -
发送请求
当我们点击按钮向/api/test发送请求的时候,nginx服务会自动帮我们在/api/test前面补上http://localhost,当请求路径中出现/api时,nginx就会帮我们代理转发这个请求到目标服务器http://101.200.242.117:8888,并将路径中的/api/test拼接上进行转发请求。