nginx_index - meetbill/butterfly-nginx GitHub Wiki
index 之坑
看个栗子
#对 / 所有做负载均衡 + 反向代理
location / {
proxy_redirect off;
# 后端的 Web 服务器可以通过 X-Forwarded-For 获取用户真实 IP
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_pass http://backend;
}
location = / {
# 首页处理
root ../templates;
index index.html;
}
想要访问 "/" 时精确匹配到 index.html ,其他则转发到 http://backend;
实际结果是访问 "/" 也访问到 http://backend
正确做法
#对 / 所有做负载均衡 + 反向代理
location / {
proxy_redirect off;
# 后端的 Web 服务器可以通过 X-Forwarded-For 获取用户真实 IP
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_pass http://backend;
}
location = / {
# 首页处理
root ../templates;
index index.html;
}
location = /index.html {
# 首页处理
root ../templates;
}
location = /favicon.ico {
root ../templates;
}
- (1) 处理 request_uri 结尾为 '/' 的请求,寻找到 '= /' location
- (2) 对 index 指令配置的多个文件做顺序查找,看文件是否存在
- (3) 如果存在,就结束查找过程,把这个文件附加到请求的 request_uri 后面,并且发起一个内部的 redirect
- (4) 指向到 '= /index.html' location
如果要往后端服务请求时添加固定 token 到 header 中时可以使用
proxy_set_header xxx-token "xxx";
其他
nginx 中,$request_uri 和 $uri 的区别
$request_uri
This variable is equal to the *original* request URI as received from the client including the args. It cannot be modified. Look at $uri for the post-rewrite/altered URI. Does not include host name. Example: "/foo/bar.php?arg=baz"
这个变量等于从客户端发送来的原生请求 URI,包括参数。它不可以进行修改。$uri 变量反映的是重写后 / 改变的 URI。不包括主机名。例如:"/foo/bar.php?arg=baz"
$uri
This variable is the current request URI, without any arguments (see $args for those). This variable will reflect any modifications done so far by internal redirects or the index module. Note this may be different from $request_uri, as $request_uri is what was originally sent by the browser before any such modifications. Does not include the protocol or host name. Example: /foo/bar.html
这个变量指当前的请求 URI,不包括任何参数(见 $args)。这个变量反映任何内部重定向或 index 模块所做的修改。注意,这和 $request_uri 不同,因 $request_uri 是浏览器发起的不做任何修改的原生 URI。不包括协议及主机名。例如:"/foo/bar.html"
$document_uri
The same as $uri.
同 $uri.
说白了,就是一个带参数,一个不带参数