Configuring auth basic Nginx

Even if you don’t know what Basic Auth is yet, you probably have already encountered it, for example, when entering the router configuration interface. This is a web server-level username and password authorization mechanism. This authorization is supported in both Apache and Nginx.

In this article, we will understand how to configure Basic Auth Nginx, for a specific route or for the entire site.

Configuring Basic Auth in Nginx

The Basic Auth authorization window looks like this:

I think now you know what I’m talking about. This authorization can be configured for a specific URL, for the entire site, or for all sites. But first you need to create a file with a list of users and passwords. To do this, use the htpasswd utility. The syntax of the command is as follows:

$ sudo htpasswd -c / path/to / file user_name

The-c option is used to create a new file, but you don’t need to use it to edit existing files. For example:

sudo htpasswd -c /etc/nginx/basic.auth admin

The utility will ask for the password twice. The password is entered but not displayed. This is how it should be for security. After the file is created, you can proceed to configuring Nginx.

To protect all your sites with a password, simply add this directive to the http section of the /etc/nginx/nginx.conf file:

auth_basic "Restricted area";
auth_basic_user_file /etc/nginx/auth.basic;

To protect only a specific URL, add the same directives to the desired location block. For example, for /wp-admin/admin-ajax.php:

location /wp-admin/admin-ajax.php {
auth_basic "Restricted area";
auth_basic_user_file /etc/nginx/auth.basic;

For WordPress, it is better to place such a location nested in location /. Then all the rules described there will work, plus your access protection. If, on the contrary, you need to allow access for a specific location, then the directive will look like auth_basic “off”. For example:

location /wp-admin/admin-ajax.php {
auth_basic "off";
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_index index.php;
include /etc/nginx/fastcgi_params;

Here, you can no longer place this location block nested, so you should add php processing to it, otherwise the web server will simply offer users to download the php script they are accessing.


As you can see, authorization with the nginx password is not so difficult to configure, you just need to correctly formulate the location block. If you still have questions, ask in the comments!


(Visited 9 times, 1 visits today)

Leave a Reply

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