Nginx配置文件中特定端点基础认证禁用失效问题求助
解决Nginx特定端点无法禁用基础认证的问题
问题原因
你的配置里,虽然给特定端点的location设置了auth_basic off,但Nginx的请求匹配逻辑导致这些请求最终还是会进入匹配.php的正则location,而这个正则location继承了server块的全局基础认证规则,所以访问这些端点时仍会要求输入账号密码。
Nginx的location匹配优先级是:精确匹配(=)> 前缀匹配(^~)> 最长前缀匹配 > 正则匹配(~/~*)。你配置的.php正则location优先级高于普通前缀location,当请求重写到index.php后,就会触发这个正则location的认证规则。
解决方案
给需要禁用认证的端点location添加^~前缀,确保它的匹配优先级高于.php的正则location,同时在这些location内添加请求处理逻辑(和根location一致的try_files规则),让请求在该location内完成转发,避免落入继承认证规则的.php正则location。
修改后的完整配置
upstream fpm_backend { server unix:/run/php/php8.1-fpm.sock; keepalive 256; } server { listen 80 default_server; server_name _; root /home/xxxx/xxxx/public; add_header X-Frame-Options "SAMEORIGIN"; add_header X-XSS-Protection "1; mode=block"; add_header X-Content-Type-Options "nosniff"; index index.html index.htm index.php; charset utf-8; error_page 404 /index.php; auth_basic "Restricted access"; auth_basic_user_file /etc/nginx/.htpasswd; location / { try_files $uri $uri/ /index.php?$query_string; } location ^~ /api/provider/aleaplay/callback/transactions { auth_basic off; try_files $uri $uri/ /index.php?$query_string; } location ^~ /api/provider/aleaplay/callback/players/ { auth_basic off; try_files $uri $uri/ /index.php?$query_string; } location ^~ /callback { auth_basic off; try_files $uri $uri/ /index.php?$query_string; } location ^~ /api/providers/bgaming/play { auth_basic off; try_files $uri $uri/ /index.php?$query_string; } location ^~ /api/providers/bgaming/rollback { auth_basic off; try_files $uri $uri/ /index.php?$query_string; } location = /favicon.ico { access_log off; log_not_found off; } location = /robots.txt { access_log off; log_not_found off; } location /web.config { return 404; } location ~ \.php$ { fastcgi_pass fpm_backend; fastcgi_index index.php; fastcgi_split_path_info ^(.+\.php)(/.+)$; include fastcgi_params; } location ~ /\.(?!well-known).* { deny all; } client_max_body_size 20M; }
验证方法
修改配置后,执行nginx -t验证配置语法无误,再执行systemctl reload nginx重载配置,然后测试访问目标端点,确认不再弹出认证窗口。
内容的提问来源于stack exchange,提问作者toma margishvili
相关产品推荐
相关产品推荐

