nginx – 找不到位置重写

我试图redirect不同的URI请求到不同的EC2容器,我一直使用nginx作为一个catchall反向代理到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; } } 

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

使用通用代理设置创建一个文件/ 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;} 

具有完全匹配的位置可能稍微更高效一些,只要你不需要很多重复的结果就不会使配置变得不实用

看看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; } } 

经过一些更多的搜索,我发现在堆栈溢出这个类似的问题,帮助我解决了我的问题:

一个规则正则表达式的nginx多个位置