为特定 URL 启用 Nginx 身份验证

为特定 URL 启用 Nginx 身份验证

我正在使用控制面板,需要在管理员访问中进行身份验证。

我已经创建了用户和密码,nginx的配置如下:

server {
listen 443 ssl;
server_name localhost;
root /usr/local/pannel/www;

gzip on;
gzip_http_version  1.1;
gzip_comp_level    5;
gzip_min_length    256;
gzip_proxied       any;
gzip_vary          on;

gzip_types
  application/atom+xml
  application/javascript
  application/json
  application/rss+xml
  application/vnd.ms-fontobject
  application/x-font-ttf
  application/x-web-app-manifest+json
  application/xhtml+xml
  application/xml
  font/opentype
  image/svg+xml
  image/x-icon
  text/css
  text/plain
  text/x-component;

ssl_certificate     /usr/local/svmstack/nginx/ssl/ssl.crt;
ssl_certificate_key /usr/local/svmstack/nginx/ssl/ssl.key;
ssl_session_timeout 6m;
ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers         HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;

index index.php;

include services/custom/legacy-master-before-php-location-443.conf;

location ~ \.php$ {
    include services/custom/legacy-master-inside-php-location-443.conf;
    try_files $uri =404;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_read_timeout 3600;
    fastcgi_pass unix:/usr/local/svmstack/fpm/socket/web.sock;
    fastcgi_index index.php;
    include fastcgi.conf;
    fastcgi_param HTTPS $https;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
include services/custom/legacy-master-after-php-location-443.conf;
}

我可以简单地将下面的代码添加到中location,但在这种情况下它会要求对/usr/local/pannel/www;文件夹中的所有文件进行身份验证。

auth_basic "Restricted";
auth_basic_user_file /usr/local/pannel/htpasswd;

如何在同一键内为特定 URL 创建新位置,在这种情况下文件位于:/usr/local/pannel/www/admin/login.php

我只需要在访问此文件(login.php)时请求身份验证。

答案1

定义需要身份验证的位置

location /admin/login.php {
  auth_basic "Restricted";
  auth_basic_user_file /usr/local/pannel/htpasswd;

  # anything else required
}

相关内容