This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function basic_auth(){ | |
nocache_headers(); | |
if ( is_user_logged_in() ) | |
return; | |
// WordPress のユーザー認証で BASIC 認証ユーザー/パスワードをチェック | |
$user = isset($_SERVER["PHP_AUTH_USER"]) ? $_SERVER["PHP_AUTH_USER"] : ''; | |
$pwd = isset($_SERVER["PHP_AUTH_PW"]) ? $_SERVER["PHP_AUTH_PW"] : ''; | |
if ( !is_wp_error(wp_authenticate($user, $pwd)) ) { | |
return; | |
} | |
// BASIC 認証が必要 | |
header('WWW-Authenticate: Basic realm="Please Enter Your Password"'); | |
header('HTTP/1.0 401 Unauthorized'); | |
echo 'Authorization Required'; | |
die(); | |
} | |
add_action('template_redirect','basic_auth'); |
ただし、Nginx のリバースプロキシキャッシュとか WP Super Cache が有効になってる場合は、正常に動作しないので注意
追記:
最初に nocache_headers();
を追加したので、Nginx のリバースプロキシキャッシュにキャッシングされなくなりました。
WP Super Cache については知らん
コメントを残す