Send by LINE
B! Bookmarks in Hate-bu
Bookmarks in Pocket
RSS feeds

nginx: Use basic authentication

Other language site
No available translations found
Google Translate
nginx logo

It is a method of basic authentication with web server nginx.

nginx does not use .htaccess file.

Installing the htpasswd command

Use the htpasswd command to create a username password for basic authentication. You need to install it if it is not installed on your OS.

Here is the installation method in CentOS.

If nothing is declared, subsequent execution users are all superusers.

yum install httpd-tools

Create .htpasswd file

Use the htpasswd command to add the basic authentication username and password.

htpasswd -c /etc/nginx/.htpasswd [username]

Then you will be prompted for a password at the command prompt.

New password:

Enter the password and press the Enter key.

Re-type new password:

Since you are prompted to re-enter the password, set the same password.

The specified password file is created. The content is like this.


Apply basic authentication to nginx configuration file

Apply basic authentication to the nginx configuration file you are using.


location ~* /wp-login\.php|/wp-admin/((?!admin-ajax\.php).)*$ {
    satisfy any;
    deny all;
    auth_basic "basic authentication";
    auth_basic_user_file "/etc/nginx/.htpasswd";
    location ~ [^/]\.php(/|$) {
        fastcgi_split_path_info ^(.+?\.php)(/.*)$;
        if (!-f $document_root$fastcgi_script_name) {
            return 404;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_buffers 256 128k;
        fastcgi_buffer_size 128k;
        fastcgi_intercept_errors on;
        fastcgi_read_timeout 120s;

Basic authentication setting is done from line 1 to line 6.

Lines 7 to 20 use the php-fpm also on the basic authentication page, so the setting contents.

The path specified by location specifies the WordPress user login screen and management screen as the basic authentication target page.

satisfy any

Specify this when basic authentication is used only for access from a specific host.

In this case, the meaning of the setting is as follows.

allow: Host not using basic authentication

deny: Host using basic authentication

In the sample code, we are using basic authentication for all access from within the server itself.

satisfy all

Specify this when using basic authentication for access from all hosts.

allow: Host using basic authentication

deny: Access denied

Notice that the meaning of allow and deny changes depending on the value of satisfy.

Restart nginx

Restart the web server to reflect the setting contents.

systemctl restart nginx
Leave a Reply