how to redirect 403 to 404 in nginx

How to Redirect 403 to 404 in NGINX

When NGINX returns 403 HTTP response code it means that the user is not authorized to access the requested URL. Since it indicates that the URL is nevertheless correct, it can be exploited by attackers to send malicious requests to such URLs. So it is advisable to redirect 403 to 404 response code so that the user does not know that the page exists. Here are the steps to redirect 403 to 404 in NGINX.


How to Redirect 403 to 404 in NGINX

Here are the steps to redirect 403 to 404 in NGINX.


1. Create 404 page

First we create an html page to be returned when server returns 404 response code. Open terminal and run the following command to create a page (say 404.html) that will be returned as a 404 response. Please note, this page has to be created in your website’s root folder. If you have already created for responding to 404 status codes, then you can skip this step.

$ sudo vi /var/www/html/404.html

Save and exit this file.

Also read : How to Enable Keep Alive in NGINX


2. Redirect 403 response to 404

We will use error_page NGINX directive to return 404.html page when server returns 403 response. error_page directly returns the specified html page when it encounters the specified response code. Here is the syntax of error_page directive.

error_page response_code path_to_html_file

You need to mention the error response code and the file to be returned for its response.

Open NGINX server configuration file.

$ sudo vi /etc/nginx/nginx.conf

Add these lines to your NGINX server configuration file (at /etc/nginx/nginx.conf) inside the server block.

server {
...
   error_page 404 /404.html
   error_page 403 = 404 /404.html
...
}

The above two lines tell NGINX to return 404.html file whenever there is a 403 or 404 response.

Also read : How to Redirect Subdirectory to Root in NGINX


3. Restart NGINX Server

Restart NGINX server to apply changes.

$ sudo nginx -t 
$ sudo systemctl restart nginx


That’s it. Now NGINX web server will return 404 file we created above, when there is a 403 status code response. If you use Apache server, you may also want to read how to redirect 403 to 404 in Apache server.


Leave a Reply

Your email address will not be published. Required fields are marked *