You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx强制返回本地文件而非Web URL的认证后服务问题

Fixing Nginx 403 & Infinite Redirect Issues for Protected m3u8 Streams

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:

  1. You’re stripping the .m3u8 extension, but your actual local file is /stream/asd.m3u8—so the rewritten path doesn’t point to an existing file.
  2. Without a flag like last or break, 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 alias with regex, always include the captured group ($1) in the alias path to build the correct file location.
  • Don’t skip adding last or break to rewrite rules unless you explicitly want Nginx to keep processing the request through other blocks.

内容的提问来源于stack exchange,提问作者cagri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:34:17