大网数据广告活动
服务器运维问答

Nginx - Node api in subfolder and static files on /

· 52CE 我爱测

I want to be able to access my api server (running on node) from a subfolder /api/ and send all other requests to my angular app. Currently the api is running on a different subdomain and my config looks like this -- server { lis…

问题原文

原帖链接 · charsi · CC BY-SA 3.0

I want to be able to access my api server (running on node) from a subfolder /api/ and send all other requests to my angular app.

Currently the api is running on a different subdomain and my config looks like this --

server {
  listen       80;
  server_name  appapi.site.com;
  location / {
    proxy_pass          http://localhost:3000/;
    proxy_http_version 1.1;
    proxy_set_header    Host             $host;
    proxy_set_header    X-Real-IP        $remote_addr;
    proxy_set_header    X-Forwarded-For  $proxy_add_x_forwarded_for;
    proxy_read_timeout 1800;
    proxy_connect_timeout 1800;
  }
}


server {
  listen 80;
  server_name app.site.com;
  index index.html;
  root /var/www/html/app.site.com/;

  location / {
    try_files $uri /$uri /index.html;
  }
}

I tried changing the location for the api to /api/ instead of / but then I can't reach my app.

Don't want to serve static files from node so please don't suggest that.

已采纳解答

原帖链接 · shonky linux user · CC BY-SA 3.0

I assume you want to serve http://app.site.com/api/xxx Adding a second location block for your /api/ path will send any URI commencing with /api/ to the proxy, and anything else to your angular app.

server {
  listen 80;
  server_name app.site.com;
  index index.html;
  root /var/www/html/app.site.com/;

  location / {
    try_files $uri /$uri /index.html;
  }

  location /api/ {
    proxy_pass          http://localhost:3000/;
    proxy_http_version 1.1;
    proxy_set_header    Host             $host;
    proxy_set_header    X-Real-IP        $remote_addr;
    proxy_set_header    X-Forwarded-For  $proxy_add_x_forwarded_for;
    proxy_read_timeout 1800;
    proxy_connect_timeout 1800;
  }
}

The proxy configuration will not strip /api/ from the path, and the URI is presented in full to your api server. This is controlled by the trailing slash in proxy_pass http://localhost:3000/. Refer to https://stackoverflow.com/questions/22759345/nginx-trailing-slash-in-proxy-pass-url for more information about this.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2018-02-20)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。