ryoakg
9/19/2016 - 6:01 AM

htaccess を使ってとりあえず簡単にBasic認証する為のコマンド

htaccess を使ってとりあえず簡単にBasic認証する為のコマンド

#!/bin/sh

# htaccess を使ってとりあえず簡単に Basic認証する為のコマンド
# 手順を書いても読むのが面倒だったり、正しいか疑わしくなるのでコマンド化

htaccess=".htaccess"
password_file=".htpasswd"

usage(){
  [ -z "$1" ] || printf "$1\n\n"
  printf "Usage: $0 <id> <password>\n"
  exit 1
}

id=$1
[ -z "${id}" ] && usage
password=$2
[ -z "${password}" ] && usage

type htpasswd > /dev/null 2>&1 || usage 'ERROR: `htpasswd` command required.'
htpasswd -c -b ${password_file} ${id} ${password}

if [ ! -e ${htaccess} -o -z "`grep AuthUserFile ${htaccess} 2> /dev/null`" ] ; then
  printf "Appending authentication config to ${htaccess}.\n"
  cat <<EOF >> ${htaccess}

### GENERATED BY $0 ###
AuthUserFile $(pwd)/${password_file}
AuthGroupFile /dev/null
AuthName "Type your ID and Password."
AuthType Basic
require valid-user
EOF
fi