Nginx新增htpasswd認證

2021-06-21 14:13:52 字數 2457 閱讀 4375

一.需求描述

nginx作為web server的服務。因業務需要在訪問**時,加一層認證資訊,以防止公司之外的人訪問**。需求類似於apache那樣為指定的目錄新增訪問驗證,一般在apache下使用htpasswd來新增。這裡是為nginx新增。

二.編寫以下程式

環境:需要支援perl。(因為用到perl)

vi htpasswd.sh

#!/bin/bash

path=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin

export path

echo "***********************************=="

echo "# a tool like htpasswd for nginx    #"

echo "#-----------------------------------#"

echo "# author:licess #"

echo "***********************************=="

#set username

username=""

read -p "please input username:" username

if [ "$username" = "" ]; then

echo "error:username can't be null!"

exit 1

fiecho "*************************=="

echo "username was: $username"

echo "*************************=="

#set password

unpassword=""

read -p "please input the password:" unpassword

if [ "$unpassword" = "" ]; then

echo "error:password can't be null!"

exit 1

fiecho "*************************=="

echo "password was: $unpassword"

echo "*************************=="

password=$(perl -e 'print crypt($argv[0], "pwdsalt")' $unpassword)

#set htpasswd file

htfile=""

read -p "please input auth filename:" htfile

if [ "$htfile" = "" ]; then

echo "error:auth filename can't be null!"

exit 1

fiecho "*************************=="

echo "auth file: /longxibendi/nginx/conf/$htfile"

echo "*************************=="

get_char()

echo ""

echo "press any key to creat...or press ctrl+c to cancel"

char=`get_char`

if [ ! -f /longxibendi/nginx/conf/$htfile.conf ]; then

make -p /longxibendi/nginx/conf/$htfile.conf 

echo "create auth file......"

cat >/longxibendi/nginx/conf/$htfile.conf三.生成使用者名稱密碼資訊

bash htpasswd.sh

按提示輸入使用者名稱、密碼、及認證檔名。指令碼會自動生成認證檔案。記錄下指令碼返回的檔案路徑。如:/longxibendi/nginx/conf/longxibendi.auth.conf

四.修改nginx.conf配置檔案,為nginx新增auth認證配置

location ^~ /longxibendi/

或者在location後面新增,比如

location  /

}location  ~ .*\.(php|php5)$

auth_basic "authorized users only";

auth_basic_user_file /longxibendi/nginx/conf/moyi.365.auth.conf;

五.重啟nginx

cd  sbin/nginx ;./nginx -s reload

六.注意事項

每個瀏覽器初次訪問,輸入使用者名稱、密碼。只需要輸入一次,之後再開啟瀏覽器就不需要輸入了。

htpasswd命令用法詳解

apache htpasswd命令用法 htpasswd cmdpsd passwordfile username htpasswd b cmdpsd passwordfile username password htpasswd n mdps username htpasswd nb mdps u...

nginx 新增 模組

title nginx 新增 模組 date 2019 10 31 11 21 46 categories tags config nginx 說明 已經安裝好的nginx,需要新增乙個未被編譯安裝的模組 以nginx rtmp module模組為例 則需要重新編譯nginx,而不是像apache一...

Nginx 新增模組

原已經安裝好的 nginx,現在需要新增乙個未被編譯安裝的模組 nginx v 可以檢視原來編譯時都帶了哪些引數 usr local nginx sbin nginx v 原來的引數 新增的引數 步驟如下 可以通過官方檢視模組安裝例子 1.使用引數重新配置 2.編譯 make 不要 make ins...