在 nginx 中配置 proxy_pass 时,遇到了一些小坑,特加以说明,防止之后忘记。html
当加上了 / ,至关因而绝对根路径,nginx 不会把location 中匹配的路径部分代理走;nginx
location ^~ /static/ { # http://backup/。。。 不带location中的东西 # 只要proxy_pass后面有东西就不带location中的东西 proxy_pass http://www.test.com/; } # location中的匹配路径为/static/。加了/以后proxy_pass 不会加上/static/ # curl http://localhost:3000/static/index.html # proxy_pass 转发为 http://www.test.com/index.html
若是没有/,则会把匹配的路径部分也给代理走。curl
location ^~ /static/ { # 带上location中的东西 proxy_pass http://www.test.com; } # location中的匹配路径为/static/。不加 / 后proxy_pass会加上 /static/ # curl http://localhost:3000/static/index.html # proxy_pass 转发为 http://www.test.com/static/index.html
location 中 ~ (区分大小写)与 ~* (不区分大小写)标识均为正则匹配,若是的话想在这里用的话,则 proxy_pass 中的 http://backup; 后面不能带有url。google
以下写法会报错url
location ~* /static/(.*) { # 此处 location 为正则匹配,proxy_pass 后面不能有 /test proxy_pass http://www.test.com/test; }
若是 http://backup; 不带url 。这么写是没有问题的代理
location ~* /static/(.*) { # 此处 location 为正则匹配,proxy_pass 后面不能有 /test proxy_pass http://www.test.com; }
proxy_pass中能够使用变量,可是若是变量涉及到域名的话 须要使用resolver指令解析变量中的域名(由于nginx一开始就会解析好域名)code
### 不涉及到域名变量 location ~* /aa/bb(.*) { # 正常使用变量,注意此处为location的正则匹配 proxy_pass 不能带 / # 转发后为 127.0.0.1:9999/test proxy_pass http://backup$1; } ### 涉及到域名的变量 location /aa/bb { # google 域名解析 resolver 8.8.8.8; # 此处变量涉及到了域名 须要调用resolver指令进行解析下不然会报错。 set $myhost "www.test.com"; proxy_pass http://$myhost; }
# curl 127.0.0.1:8888/aa/bb/ccc location /aa/bb { rewrite /aa/bb(.*) /re$1 break; proxy_pass http://backup; } # 转发后获得 127.0.0.1:9999/re/ccc location /aa/bb{ rewrite /aa/bb(.*) /re$1 break; # rewrite 重写后的 url 路径会 忽略 /asd 至关于 http://backup;什么都不带 proxy_pass http://backup/asd; } # 此处转发后一样获得 127.0.0.1:9999/re/ccc