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

nginx: directly send from location to another named location

· 52CE 我爱测

In my nginx 1.12.2 conf file, I have: upstream app { server unix:/tmp/app.sock fail_timeout=0; } server { listen 443 deferred; root /some/dir; try_files $uri @app; # If the request is for the naked domain, just serve the index bu…

问题原文

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

In my nginx 1.12.2 conf file, I have:

upstream app {
  server unix:/tmp/app.sock  fail_timeout=0;
}

server {
  listen 443 deferred;

  root /some/dir;

  try_files $uri @app;

  # If the request is for the naked domain, just serve the index bundle
  # without going through Rails
  #
  location = / {
    try_files /index.html =404;
  }

  # If the request if for the /api prefix, go directly to Rails.
  # This location block is not strictly required, but it could be a handy
  # customization hook for extra headers and settings.
  #
  location /api/ {
    # Extra conf!
    try_files @app;
  }

  # The location directory allows very creative configurations.
  # http://nginx.org/en/docs/http/ngx_http_core_module.html#location
  #
  # This is just a named location to be used in try_files.
  location @app {
    proxy_pass_request_headers on;
    proxy_set_header ...
    proxy_pass http://app;
  }
}

There, this is not really right because it has a single argument:

  location /api/ {
    # Extra conf!
    try_files @app;
  }

...but it communicates well what I'm trying to achieve. I suppose I could get try_files to work by adding a non-esitent file before the last argument.

Is try_files the only way to do it, or is there another more idiomatic directive?

已采纳解答

原帖链接 · Richard Smith · CC BY-SA 4.0

Your scheme will not work. When nginx settles on the final location block to process the request, it will use the "settings and headers" that are in scope, which may be inherited from a surrounding block, but will not include any "extra headers and settings" from sibling blocks - irrespective of the process taken to find the final location block. See request_processing docs for more.

If you have common statements applicable to a number of locations, you can offload them to a separate file and include them where necessary. For example:

location / {
    try_files $uri @app;
}
location /api/ {
    # Extra conf!
    include my/proxy/conf;
}
location @app {
    include my/proxy/conf;
}

See include doc for more.

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

资料来源与适用范围

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

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

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