Catalogue
Configuring Nginx Basic Authentication and Allowing Only Specific IPs Such as the Office Network

Configuring Nginx Basic Authentication and Allowing Only Specific IPs Such as the Office Network

🌐 日本語で読む

Overview

Before releasing a service, I needed to put Basic authentication in front of it with Nginx.

It happened to coincide with an internal rollout, and since the Basic authentication popup was annoying, I wanted to turn it off only for the office network. To do that, I used the configuration below.

Configuring Basic Authentication

1
# yum install -y httpd-tools
1
2
3
4
# cd /etc/nginx
# htpasswd -c .htpasswd <Basic認証ユーザ>
New password: <Basic認証ユーザのパスワード入力>
Re-type new password: <もう一度、Basic認証ユーザのパスワード入力>

Editing the Nginx Configuration File

1
# vim /etc/nginx/conf.d/default.conf
1
2
3
4
5
6
7
8
9
10
location / {
....

# Basic認証設定
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;

....
}

When You Want to Allow Only Specific IPs

1
# vim /etc/nginx/conf.d/default.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
location / {
....

# add start -----
satisfy any;
allow <許可IP>;
allow <許可IP>;
deny all;
# add end -----

# Basic認証設定
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;

....
}

After that, you can keep adding allowed IPs as needed.

I think this is a pretty common Nginx scenario in web application development.

That’s it.

kenzo0107

kenzo0107