大网数据广告活动
服务器运维问答

Apache2 HTTP authentication: don't ask for credentials, return 401 immediately

· 52CE 我爱测

I have an Apache 2.4 webserver that serves some files that should be visible to the public, and others that should only be visible after authentication, which I have implemented with the AuthType Basic directive in a .htaccess fi…

问题原文

原帖链接 · morph · CC BY-SA 4.0

I have an Apache 2.4 webserver that serves some files that should be visible to the public, and others that should only be visible after authentication, which I have implemented with the AuthType Basic directive in a .htaccess file.

The restricted files will never be accessed by a human with a browser, but only from software that requests them and includes the authentication credentials in the HTTP header.

If the site is accessed without providing the credentials directly in the header (e.g. with a browser), I want Apache to return a 401 Unauthorized status immediately and not show the authentication dialog. Is that possible?

已采纳解答

原帖链接 · MrWhite · CC BY-SA 4.0

You can't do this by only sending the 401 Unauthorised response (as @davidgo has already pointed out). However, you can't just send another 4xx status instead either; you need both.

You need HTTP Basic Authentication (ie. a potential "401 Unauthorized" response) when the Authorization HTTP request header is sent from your software, but respond with a 403 Forbidden when authentication has not been attempted on the initial request (ie. a default browser request).

On Apache 2.4, you can use Apache expressions to make this conditional...

# Check if "Authorization: Basic ..." HTTP request header has been sent 
<If "%{HTTP:Authorization} =~ /^Basic\s./">
    AuthType Basic
    AuthName "Private Area"
    AuthUserFile "/home/user/.htpasswds/secret"
    Require valid-user
</If>
<Else>
    # 403 Forbidden all requests that have not sent an "Authorization" header
    Require all denied
</Else>

Providing the software sends the correct credentials in the Authorization header then it should be allowed access. If your software should send the wrong credentials then the expected 401 Unauthorized response will be returned. Otherwise, any request that does not send an Authorization header will simply get a 403 Forbidden and no password prompt.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2019-10-08)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。