Nginx反向代理配置之proxy_pass

一、环境准备

使用express准备解析路径的应用
本来准备使用Flask, 不过没找到路由通配符的实现方法

1、server.js

const express = require("express");

const app = express();

app.get("*", (request, response) => {
    response.send(request.path)
})

const port = 8081;

app.listen(port, () => {
    console.log(`server at: http://127.0.0.1:${port}`);
})

访问:http://127.0.0.1:8081/

2、配置本地DNS
/etc/hosts

127.0.0.1       www.demo.com

3、配置Nginx
demo.com.conf

server {
  listen 80;

  server_name www.demo.com;

  location / {
      proxy_pass http://127.0.0.1:8081/;
  }
}

访问:http://www.demo.com/

二、简单示例

location匹配的网址

location /      # 普通 location
location ^~ /   # ^表示 “非”,~ 表示 “正则”,意思是:不要继续匹配正则 

先看一个简单的例子:
配置1:

location /api {
    proxy_pass http://127.0.0.1:8081/;
}

# 访问 | 返回两个路径
http://www.demo.com/api   /
http://www.demo.com/api/  //

配置2:

location /api/ {
    proxy_pass http://127.0.0.1:8081/;
}

# 访问 | 返回一个路径
http://www.demo.com/api   /   # 网址会自动加/
http://www.demo.com/api/  /

所以,为了减少变量,配置location的地址,都在结尾加上/

三、测试

访问的地址都是:
http://www.demo.com/api/index.html

proxy_pass return
http://127.0.0.1:8081 /api/index.html
http://127.0.0.1:8081/ /index.html
http://127.0.0.1:8081/admin /adminindex.html
http://127.0.0.1:8081/admin/ /admin/index.html

所以,还是proxy_pass以/ 结尾比较容易记忆

参考
nginx 反向代理之 proxy_pass

发布了1449 篇原创文章 · 获赞 400 · 访问量 142万+

猜你喜欢

转载自blog.csdn.net/mouday/article/details/105010864
今日推荐