最近處理一個舊網站,因為是 demo 用途所以帳號密碼基本上都隨便設定。但是我不想給陌生人掃進來 try error ,所以想到在 Nginx 上上添加 auth_basic 的功能。
環境如下:
- 這個舊網站非常舊,是 ThinkPHP 的 5.x.x 版本
- 裡面會 php 設定網址後綴 .html 所以網址會變成 https://xxx.xxx/PATH/ooooo.html 這樣
先上注意事項:
- 我最後選擇保護 .php 檔案,如果有其他需要保護的,甚至靜態檔案請確保 location 的設定。
- 因為是 location 選擇 php 檔案,所以驗證通過以後要走一樣的操作順序。
- 得自首一下,這部分我 try error 很久,是試出來的結論。書到用時方恨少,以後有機會記得補上有系統的原理原則。
- 建議使用 HTTPS 避免 header 的帳密被中間人攻擊。
- auth_basic 幾個基本知識網路上滿多的,參考這裡、這裡和這裡。
補上程式碼:
/PATH_AUTH_BASIC/auth_basic.conf
# Directory protection rules
location ~* \.php$ {
auth_basic "Authorization";
auth_basic_user_file /PATH/Need_Password.pass;
# 如果驗證通過則走 PHP 動作
include PHP-73.conf;
# 如果是靜態的 .html 文件,則直接嘗試提供
rewrite ^(.*)$ /index.php?s=$1 last; break;
}
而操作順序, 在 server 的 block 裡面如下:
...
#Directory protection rules
include /PATH_AUTH_BASIC/auth_basic.conf;
#PHP reference configuration
include PHP-73.conf;
#REWRITE-START URL rewrite rule reference, any modification will invalidate the rewrite rules set by the panel
include /PATH_REWRITE/rewrite.conf;
...
補上 ThinkPHP 的 rewrite.conf 主要的設定:
...
location / {
if (!-e $request_filename){
rewrite ^(.*)$ /index.php?s=$1 last; break;
}
try_files $uri $uri/ =404;
}
...