一个Nginx错误代码的位置块

40

是否可能通过一个单一的位置规则来处理40x和50x错误?例如:

error_page 403 /403.html;
error_page 404 /404.html;
error_page 405 /405.html;
error_page 500 501 502 503 504 /5xx.html;

location ~ /(?:40[345]|5xx)[.]html$ {
    root /var/www/default/error;
}
2个回答

104

21
优秀的解决方案。如果有人完全不了解这个,需要注意你仍然需要在 /var/www/default 目录下创建 "error" 文件夹。 - Frug
9
可以使用alias代替root,这样文件将直接从/var/www/default/读取,而不是/var/www/default/error/ - m4tx
2
我想要一个服务器块,它可以响应任何未配置的服务器名称(例如,在IP地址上会提供404页面)。我希望该页面是自定义的。我写了:listen 80 default_server; server_name default; return 404; error_page 404 /errors/404.html; location ^~ /errors/ { internal; root /var/www; }。但我仍然得到默认的nginx 404错误页面。return 404;与自定义页面一起使用吗? - Kitet
3
好的,我会尽力为您翻译。以下是需要翻译的内容:提示:如果您的错误页面使用与同一目录下的图像、CSS 等静态文件,请省略 internal; - igo

1

动态HTTP响应页面可以响应在Nginx源代码src/http/ngx_http_header_filter_module.c中定义的所有HTTP响应码。

## Nginx source code file to extract HTTP response codes from
$ NGINX_SRC_URL="https://raw.githubusercontent.com/nginx/nginx/master/src/http/ngx_http_header_filter_module.c"

### Find values double quotes that match lines 'ngx_string("### '
$ curl --silent $NGINX_SRC_URL | egrep 'ngx_string\(\"[0-9]{3} .*\"' | cut -d\" -f2 | sort

# OUTPUTS
200 OK
201 Created
202 Accepted
...

Nginx配置

# in http {} block

error_page
  301 302 303 304 307 308
  400 401 402 403 404 405 406 408 409 410 411 412 413 414 415 416 421 429
  500 501 502 503 504 505 507
  @errors;

map $status $status_text {
  default "Unknown error";
  200 "OK";
  201 "Created";
  202 "Accepted";
  204 "No Content";
  206 "Partial Content";
  301 "Moved Permanently";
  302 "Moved Temporarily";
  303 "See Other";
  304 "Not Modified";
  307 "Temporary Redirect";
  308 "Permanent Redirect";
  400 "Bad Request";
  401 "Unauthorized";
  402 "Payment Required";
  403 "Forbidden";
  404 "Not Found";
  405 "Not Allowed";
  406 "Not Acceptable";
  408 "Request Time-out";
  409 "Conflict";
  410 "Gone";
  411 "Length Required";
  412 "Precondition Failed";
  413 "Request Entity Too Large";
  414 "Request-URI Too Large";
  415 "Unsupported Media Type";
  416 "Requested Range Not Satisfiable";
  421 "Misdirected Request";
  429 "Too Many Requests";
  500 "Internal Server Error";
  501 "Not Implemented";
  502 "Bad Gateway";
  503 "Service Temporarily Unavailable";
  504 "Gateway Time-out";
  505 "HTTP Version Not Supported";
  507 "Insufficient Storage";
}

##  in server {} block

location @errors {
  internal;
  default_type "text/plain; charset=utf-8";
  return 200 "$status $status_text\n";
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接