问题原文
原帖链接 · 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.
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
