Nginx: How to rewrite the path to the error page?

ni flag

I have an /api location that contains an HTTP authorization. I want my 401 page to be displayed on failed authorization.

Here is my file structure (If it's important, I'm running nginx on Windows)

  | 401.html
    | script.js
    | styles.css

Here is my config

server {
    listen 80;
    error_page 401 /401.html;
    location = /401.html {
        auth_basic off;
        root html;

    location /api {
        auth_basic "Restricted area";
        auth_basic_user_file ../conf/conf.d/htpasswd;

I got two problems

  1. If I just type in the browser, I get an error that it cannot access files in 40x_files folder (here is filed of 401.html page)

  2. If I fail the authorization, then for some reason I am redirected to this path api/40x_files/script.js, how can I return it to correct state?

I suppose I need to do some kind of rewrite, but I don’t really understand how to arrange it correctly


Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.