Nginx强制返回本地文件而非Web URL的认证后服务问题
Let’s break down exactly what’s going wrong with your current config and fix it step by step:
Why You’re Seeing 403 Forbidden
Your alias /stream/; line in a regex location block is misconfigured. When using regular expressions with alias, Nginx doesn’t automatically map captured groups to the path—instead, it appends the full matched URI to the alias directory. For a request like http://example.com/stream/asd.m3u8, this resolves to /stream//stream/asd.m3u8 (notice the duplicate /stream/), which is an invalid path. Even with chmod 777, Nginx can’t find the file, hence the 403 error.
Why You’re Getting Infinite Redirects
Your rewrite /stream/(.*)\.m3u8 /stream/$1; rule has two critical issues:
- You’re stripping the
.m3u8extension, but your actual local file is/stream/asd.m3u8—so the rewritten path doesn’t point to an existing file. - Without a flag like
lastorbreak, Nginx will keep processing the rewritten request through location blocks again. If the new path accidentally loops back to this location, you hit the redirect limit.
The Correct Configuration
Here’s a fixed setup that handles authentication and correctly maps requests to your local file:
location ~ ^/stream/(.*)\.m3u8$ { # Re-enable your authentication here once debugging is done auth_basic "Stream Access Restricted"; auth_basic_user_file /path/to/your/.htpasswd; # Correctly map the request to the local file using the captured group alias /stream/$1.m3u8; # Optional: Add streaming-specific headers if needed add_header Cache-Control "no-cache"; }
Alternative Using root (Simpler for Some)
If regex with alias feels confusing, use root instead. This works because root appends the full URI to the specified directory:
location ~ ^/stream/(.*)\.m3u8$ { auth_basic "Stream Access Restricted"; auth_basic_user_file /path/to/your/.htpasswd; root /; # Points to the Linux root directory try_files $uri =404; # Ensures we only serve existing files }
Key Tips to Avoid Future Issues
- Use
^and$in regex location blocks to match the exact start/end of the URI—this prevents unintended partial matches. - When using
aliaswith regex, always include the captured group ($1) in the alias path to build the correct file location. - Don’t skip adding
lastorbreakto rewrite rules unless you explicitly want Nginx to keep processing the request through other blocks.
内容的提问来源于stack exchange,提问作者cagri

