node.js – 使用nginx处理Express子域

前端之家收集整理的这篇文章主要介绍了node.js – 使用nginx处理Express子域前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我想知道我如何处理基于Expressjs的项目中的子域名.

这是我的Nginx配置

server {
  listen 80;
  server_name           bee.local;

  access_log            /var/log/Nginx/bee.local.access.log;
  error_log             /var/log/Nginx/bee.local.error.log;

  location / {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header X-Forwarded-For $remote_addr;
  }
}

server {
  listen 80;
  server_name           api.bee.local;

  access_log            /var/log/Nginx/bee.local.access.log;
  error_log             /var/log/Nginx/bee.local.error.log;

  location / {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header X-Forwarded-For $remote_addr;
  }
}

这是我的子域支持路由器

router.get('/v1/',function(req,res,next) {
    res.status(200).json({ title: "title" });
});



app.use(subdomain('api',router));

问题是它正在呈现索引路由

并且肯定我设置了hosts文件

我一直在寻找3小时你能帮我:)

最佳答案
有几个要求:

>在Nginx中使用必需的域或代理设置主机头(如果适用)
>在处理端点的其他中间件之前使用子域中间件

工作示例:

Nginx配置:

server {
    listen       80;
    server_name  bee.local;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Host      $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

server {
    listen       80;
    server_name  api.bee.local;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Host      $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

具有硬编码主机头值的Nginx配置:

我相信你没有正确设置主机头.请尝试下一个配置

server {
    listen       80;
    server_name  bee.local;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
#        proxy_set_header Host      $host;
        proxy_set_header Host      bee.local;
    }
}

server {
    listen       80;
    server_name  api.bee.local;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
#        proxy_set_header Host      $host;
        proxy_set_header Host      api.bee.local;
    }
}

快递应用:

var subdomain = require('express-subdomain');
var express = require('express');
var app = express();

var router = express.Router();

router.get('/',res) {
  res.send('Welcome to our API!');
});

router.get('/users',res) {
  res.json([
    { name: "Brian" }
  ]);
});

app.use(subdomain('api',router));

app.get('/',res) {
  res.send('Homepage');
});

app.listen(3000);

猜你在找的Nginx相关文章