nginx下使用HTTP basic auth保护网站目录。
最近因远程测试数据问题,安装phpmyadmin数据库管理工具,为了加强安全性,用nginx做了 auth basic 验证。
基于同一个nginx虚机(server块)下,把phpmyadmin改名为data-manager放到nginx虚机的根目录,增加location作用域:
location /data-manager/ {
index index.html index.htm index.php;
auth_basic "Please Login!";
auth_basic_user_file /usr/local/nginx/conf/auth/nginxpwd;
}
要注意的是 location /data-manager/是以/data-manager/开头的,与location / 二选一,所有要增加一个 index 设置。基于https的完整配置代码如下。
# HTTPS server
server {
listen 443 ssl;
server_name www.mydomain.com;
root /data/server_data/nginx/html/www.mydomain.com;
ssl_certificate /usr/local/nginx/conf/ssl/www.mydomain.com/1_www.mydomain.com_bundle.crt;
ssl_certificate_key /usr/local/nginx/conf/ssl/www.mydomain.com/2_www.mydomain.com.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
index index.html index.htm index.php;
try_files $uri $uri/ /index.php?$args;
}
location /data-manager/ {
index index.html index.htm index.php;
auth_basic "Please Login!";
auth_basic_user_file /usr/local/nginx/conf/auth/nginxpwd;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
如果是用 location ^~ 正则模式,因为此模式被匹配后即停止匹配其它location,还需将php的代理放入该块中才能解析php,如下所示:
location ^~ /data-manager/ {
index index.html index.htm index.php;
auth_basic "Please Login!";
auth_basic_user_file /usr/local/nginx/conf/auth/nginxpwd;
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}