使用 nginx 提供带有标头 404 的自定义 404 页面,而无需更改浏览器地址

使用 nginx 提供带有标头 404 的自定义 404 页面,而无需更改浏览器地址

如何强制 nginx 提供自定义 404 页面并使用 404 标头进行响应,而无需更改浏览器的地址以便用户轻松重新输入?

set $allowed 0; #(updated after comments)
error_page  404  /404page.html; #(updated after first answer, forgot to mention)

    location = /authreq.html {
    if ($allowed = 0){
#   return 307 $scheme://$host/404page.html ; #works but should be 404
#   return 404 "shows this message"; #does not redirect when inserting url instead of message
# rewrite ^ /404page.html break; #serves 404page.html and doesn't change browseraddress which is good, but sends a response header 200
# return 404 # invokes error_page directive with header 200 

    }
}

整体配置:

server {

    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;
    server_name www.fellowshipmedia.eu;
    server_name localhost;
    root /usr/share/nginx/html;
    index index.php index.html index.htm;
    error_page   404  =  /404page.html;
    set $allowed 0;

    location = /authreq.html {
        if ($allowed = 0){
           # return 307 $scheme://$host/404page.html ; #works but should be 404
           # return 404 "shows this message"; #does not redirect when inserting url instead of message
           return 404; #
           # rewrite ^ /404page.html break; #serves 404page.html and doesn't change browseraddress which is good, but sends a response header 200
        }
    }



}

答案1

error_page 指令不会为您做到这一点吗?

例如这样的事情:

server {
...   
  error_page  404  /404page.html;
...
  location = /authreq.html {
    if ($allowed = 0){
      return 404;
    }
  }
}

答案2

只需执行以下操作即可不会返回 404 标头,而是返回 200:

    server {
...   
  error_page  404  /404page.html;
...
  location = /authreq.html {
    if ($allowed = 0){
      return 404;
    }
  }
}

要调用 404 标头并提供自定义 404 页面而不更改浏览器的地址栏地址,您应该在 error_page 指令中添加“404”,如下所示:

    error_page   404  =404  /404page.html;

相关内容