2

我正在尝试将不同的 URI 请求重定向到不同的 EC2 容器,多年来我一直使用 nginx 作为 apache 的包罗万象的反向代理,但现在我想在 nginx 级别进行一些重写。

这是我要完成的工作:

server {
    listen       80;
    server_name  _;

    gzip              on;
    gzip_static       on;
    gzip_buffers      16 8k;
    gzip_comp_level   9;
    gzip_http_version 1.0;
    gzip_min_length   0;
    gzip_types        text/plain text/css application/x-javascript;
    gzip_vary         on;

    location / { 
        # catch the following URI's including homepage: /contact.html, /terms.html, /
        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 240;
        proxy_connect_timeout 240;
        proxy_send_timeout 240;

        send_timeout 240;
        proxy_pass http://servers_static;
    }

    location / { 
        # catch everything not matched above
        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 240;
        proxy_connect_timeout 240;
        proxy_send_timeout 240;

        send_timeout 240;
        proxy_pass http://servers_dynamic;
    }
}

我确信这只是一个简单的正则表达式问题,但我从来没有理解过那些东西。有人可以帮我吗?

4

2 回答 2

2

使用通用代理设置创建文件 /etc/nginx/EC2:

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 240;
proxy_connect_timeout 240;
proxy_send_timeout 240;
send_timeout 240;

然后您的主要配置变为:

server {
  listen       80;
  server_name  _;

  #gzip settings cut for brevity, add them back in     

  # static content
  location = / {include /etc/nginx/EC2; proxy_pass http://servers_static;}
  location = /contact.html {include /etc/nginx/EC2; proxy_pass http://servers_static;}
  location = /terms.html {include /etc/nginx/EC2; proxy_pass http://servers_static;}

  # dynamic content
  location / { include /etc/nginx/EC2; proxy_pass http://servers_dynamic; }
}

您还可以像这样组合 .html 静态内容页面的位置:

  location ~ (contact|terms).html {
    include /etc/nginx/EC2; proxy_pass http://servers_static;}

拥有精确匹配的位置可能会更有效一些,只要你不需要很多重复的结果就不应该使配置变得笨拙

于 2012-10-13T08:01:28.437 回答
0

看看try_files。它会依次尝试你给它的路径。在此示例中,/var/www/sites/foo/current/public/$uri将返回任何静态文件,仅在不存在静态文件时将请求路由到应用程序。

upstream app {
  server unix:/tmp/.sock_my_app;
}

server {
  # path for static files
  root /var/www/sites/foo/current/public;

  # Prefer to serve static files directly from nginx to avoid unnecessary
  # requests to the application server.
  try_files $uri/index.html $uri.html $uri @app;

  location @app {
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    # timeouts

    # reverse proxy to an upstream
    proxy_pass http://app;
  }
}
于 2012-10-13T06:25:26.777 回答