try_files
ngx_http_core_module.html#try_files
Module ngx_http_core_module/try_files
| Syntax: | try_files file … uri; |
| try_files file … =code; | |
| Default: | — |
| Context: | server, location |
检查按顺序指定的文件(file)是否存在,并使用第一个找到的文件进行请求处理;处理在当前上下文中执行。文件的路径是根据 root 和 alias 指令从 file 参数构造。可以通过在 file 的末尾指定斜杠来检查目录的存在,例如,“$uri/”。如果未找到任何文件,则会进行内部重定向到由最后一个参数中指定的 uri 中。例如:
location /images/ {
try_files $uri /images/default.gif;
}
location = /images/default.gif {
expires 30s;
}
最后一个参数也可以指向命名位置,如下面的示例所示:
location / {
try_files /system/maintenance.html
$uri $uri/index.html $uri.html
@mongrel;
}
location @mongrel {
proxy_pass http://mongrel;
}
从版本 0.7.51 开始,最后一个参数也可以是 HTTP 响应码:
location / {
try_files $uri $uri/index.html $uri.html =404;
}
访问某个地址,返回固定内容:
location /client/index.php {
try_files /index.html /index.html;
}
该笔记将记录:try_files 的使用方法、常见场景的配置、常见问题的处理;
当请求某个文件时,返回特定的其他文件
location /client/index.php {
try_files /index.html /index.html;
}
文件存在,但返回 404 状态码
对于如下配置,当请求 /foo 地址时,将尝试查找 foo.html 文件,如果不存在则返回 index.html 文件:
location / {
root /srv/html/;
try_files $uri.html index.html;
}
问题原因
虽然 foo.html 不存在,但是 index.html 是存在的,然而却返回 404 状态码;
根据 try_files file … uri; 文档:当文件不存在时,将触发内部重定向到 uri 指定的地址(这里是 index.html 地址)。这是匹配不到的,因为我们没有定义 location index.html,我们应该使用 /index.html,这样能够匹配到 location / 配置;
解决方法
应该使用如下配置:
location / {
root /srv/html/;
try_files $uri.html /index.html;
}
或者定义 location index.html 配置:
location index.html {
# do some stuff
}
error_page
nginx not serving my error_page
指令「error_page」处理由 nginx 生成的错误。
默认情况下,无论 http 状态代码如何,nginx 都将返回代理服务器返回的任何内容。所有error_page不会处理proxy_pass的返回。应该使用proxy_intercept_errors on指令,然后再配置 error_page 指令。
location
遇到 301 重定向
Module ngx_http_core_module/location
如果 location 以斜线(/)结尾,并且当请求被 proxy_pass, fastcgi_pass, uwsgi_pass, scgi_pass, memcached_pass, grpc_pass 模块处理时,将进行特殊处理:
响应设置 Response
该笔记将记录:在 Nginx 中,与响应有关的常见设置,以及相关问题的解决方案;
设置响应类型
http headers – Force nginx to send specific Content-Type – Stack Overflow
default_type(Module ngx_http_core_module/default_type),设置默认 MIME 类型:
default_type application/xml; # http, server, location
type(Module ngx_http_core_module),根据文件扩展名设置返回类型:
types {
application/octet-stream bin exe dll;
application/octet-stream deb;
application/octet-stream dmg;
}
# http, server, location
注意事项,受支持的 MIME 类型参考 /etc/nginx/mime.types 文件(具体文件路径取决于发行版);
应用
场景 | 413 Request Entity Too Large
https://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size
nginx 更改配置 client_max_body_size 没有生效
Context: http, server, location
server{
...
client_max_body_size 20m;
...
}