自定义 Nginx 错误页面在生产环境中不起作用

Custom Nginx error page don't work in production

我正在尝试自定义 Nginx 错误页面。

1/我创建了一个html页面测试(这个名字400.html)

2/ 我在 /etc/nginx/snippets/ 目录中创建了一个自定义错误-page.conf 文件:

  error_page 400 /400.html;
  location = /400.html {
    root /var/www/apps/site_name/error_pages;
    internal;
  }

3/ 我在 Nginx 配置中包含自定义错误-page.conf(站点可用):

upstream site_name {
  ip_hash;
  server 0.0.0.0:8000;
}
server {
  if ($host = site_name.domain_name.fr) {
      return 301 https://$host$request_uri;
  } # managed by Certbot
  server_name site_name.domain_name.fr;
  server_tokens off;

  include /etc/nginx/domain_name_conf.d/acme_challenge.conf;
  set $error_pages_root /var/www/apps/site_name/error_pages;
  client_max_body_size 512M;
  include /etc/nginx/domain_name_conf.d/503.conf;

  location ~ /.+ {
    return       301 https://$server_name$request_uri;
  }
}

server {
  include /etc/nginx/snippets/custom-error-page.conf;
  include /etc/nginx/domain_name_conf.d/ssl_generic.conf;
  server_name site_name.domain_name.fr;
  root /var/www/apps/sources/site_name;
  set $error_pages_root /var/www/apps/site_name/error_pages;
  
  ssl_client_certificate /etc/nginx/private/ca.pem;
  ssl_verify_client optional;
  if ($ssl_client_verify != SUCCESS) {
    return 400;
  }

  ssl_certificate /etc/letsencrypt/live/site_name.domain_name.fr/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/site_name.domain_name.fr/privkey.pem;

  access_log /var/log/nginx/site_name.domain_name.fr/access.log;
  error_log /var/log/nginx/site_name.domain_name.fr/error.log;
  
  client_max_body_size 512M;
  gzip on;
  gzip_disable "msie6";
  gzip_vary on;
  gzip_proxied any;
  gzip_comp_level 6;
  gzip_buffers 16 8k;
  gzip_http_version 1.1;
  gzip_min_length 256;
  gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml image/png;
  
  include /etc/nginx/domain_name_conf.d/acme_challenge.conf;
  include /etc/nginx/domain_name_conf.d/503.conf;
  location ~ ^/(static|media)/ {
    return       301 https://site_name.fr$request_uri; 
  }
  location / {
    proxy_set_header  Host  $http_host;
    proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header  X-Forwarded-Ssl $scheme;
    proxy_redirect  off;
    proxy_set_header X-Scheme $scheme;
    if (!-f $request_filename){
      proxy_pass http://site_name;
      break;
    }
  }
}

4/ Nginx -t return ok

5/ 我重启Nginx服务-systemctl restart nginx.service

400 页面始终是 Nginx 400 页面。

我找到了解决问题的方法。 我编辑 custom-error-page.conf :

error_page 400 @bad_request;
 location @bad_request {
   root /var/www/apps/site_name/error_pages;;
   rewrite ^(.*)$ /400.html break;
 }

我的 custom-error-page.conf 文件放在了错误的地方。 我在所有服务器中和错误 400 的 return 之后都指出了它。