4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

basic認証をif文で分岐する

Last updated at Posted at 2020-09-11

htaccess の記述

結構使えそうなのでここでメモしておきます。

今回、AuthUserFileのパスを分岐する方法を載せます。
相対パスが使えないので分岐出来ないと思ったら.htaccessで分岐できることが発覚!
Apache2.4からはIfディレクティブが使えるようになりました。

普通の場合

.htaccess
# basic認証
AuthUserFile /path/to/your/.htpasswd
AuthType Basic
AuthName "Web access"
Require valid-user

分岐する場合

.htaccess
<If "req('Host') = 'www.example.com'">
    AuthUserFile /path/to/your/.htpasswd
    Authtype Basic
    AuthName "Web access"
    Require valid-user
</If>

おまけ

こういうことも出来るようです!

IPアドレスで分岐

.htaccess
<If "%{REMOTE_ADDR} != '127.0.0.1'">
    AuthUserFile /path/to/your/.htpasswd
    Authtype Basic
    AuthName "Web access"
    Require valid-user
</If>

REQUEST_URIで分岐

ここで注意!
/(スラッシュ)が \x2F になります。
/admin/.* → \x2Fadmin\x2F.*

<If "%{REQUEST_URI} =~ /\x2Fadmin\x2F.*/">
    AuthUserFile /path/to/your/.htpasswd
    Authtype Basic
    AuthName "Web access"
    Require valid-user
</If>

合わせ技

<If "req('Host') = 'www.example.com' && %{REQUEST_URI} =~ /\x2Fadmin\x2F.*/" >
    AuthUserFile /path/to/your/.htpasswd
    Authtype Basic
    AuthName "Web access"
    Require valid-user
</If>
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?