【问题标题】:nginx try_files rewrite if exists proxy if doesn'tnginx try_files 如果不存在则重写代理
【发布时间】:2017-04-07 18:08:08
【问题描述】:

我正在使用 nginx docker 容器 (https://github.com/jwilder/nginx-proxy) 将请求代理到在其他 docker 容器中运行的 apache 实例。每个子域都有自己的 apache docker 容器。这些子域之一 (sub1) 需要一些特殊规则:

如果 URL 以“foo”开头,那么我希望 nginx 检查文件是否存在。如果该文件存在,那么它应该将 URL 重写为访问控制脚本 (imageControl.php),并将其传递给通常的 apache 容器。如果文件不存在,那么我希望将请求代理到远程服务器。

我以为我设置正确,但由于某种原因,nginx 总是将请求发送到远程服务器 - 即使文件存在于本地。

这里是 docker 容器中的 nginx 配置文件的相关部分:

default.conf(包含在 nginx.conf 中):

upstream sub1.mydomain.com {
            ## Can be connect with "dockerized_default" network
            # dockerized_sub1
            server 172.18.0.2:80;
}
server {
    server_name sub1.mydomain.com;
    listen 80 ;
    access_log /var/log/nginx/access.log vhost;
    include /etc/nginx/vhost.d/sub1.mydomain.com;
    location / {
        proxy_pass http://sub1.mydomain.com;
    }
}  

/etc/nginx/vhost.d/sub1.mydomain.com:

location ^~ /foo/ {
    root /path/to/dockerized/webroot;
    try_files $uri @rewrite @remoteproxy;
}

location @remoteproxy {
   include vhost.d/remoteproxy.inc;
   proxy_pass http://remote.ip.address.here;
}

location @rewrite {
    rewrite ^/(.*)$ /imageControl.php?file=$1 break;
}

请注意,我不希望 nginx 尝试运行 imageControl.php(我没有使用 php-fpm) - 我希望 nginx 将其传递给上游 apache 容器。

期望的行为示例:

  1. 这部分有效

  2. 这部分不起作用

我将不胜感激。

【问题讨论】:

    标签: nginx reverse-proxy jwilder-nginx-proxy


    【解决方案1】:

    使用if -e 表达式可能会更幸运:

    location ^~ /foo/ {
        root /path/to/dockerized/webroot;
        if (-e $request_filename) {
            rewrite ^/(.*)$ /imageControl.php?file=$1 last;
        }
        include vhost.d/remoteproxy.inc;
        proxy_pass http://remote.ip.address.here;
    }
    

    请参阅this document 了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-24
      • 1970-01-01
      • 2013-05-17
      • 2014-04-26
      • 2013-11-27
      • 1970-01-01
      • 2013-11-29
      相关资源
      最近更新 更多