【问题标题】:nginx X-Accel-Redirect with regex internal location causes 301带有正则表达式内部位置的 nginx X-Accel-Redirect 导致 301
【发布时间】:2014-09-23 20:01:32
【问题描述】:

我对 nginx 有下一个问题。我设置了代码来提供安全文件。这是重定向请求的 PHP 代码:

$file_path = '';
$start = (isSet($_GET['start']) ? '?start='.$_GET['start'] : '');
if(check_url($org_url)){
    header("X-Accel-Redirect: /film/".$file_path.$start); die();
}
else {
    header("Location: /403.html");
    die();
}

和 check_url 函数:

function check_url($org_url){
    global $file_path;
    ...
    $file_path = $_GET['file'];
    ...
    $hash = md5(...);
    if($url_time_to > time() && $hash === $url_hash){ return true; }
    else return false;
}

然后我就有了这样的 nginx 配置:

location /file/ {
    rewrite . /file.php last;
}

location /file.php {
    internal;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

location /film {
    alias /var/www/filmy;
    mp4;
    flv;
    internal;
}

一切正常。但我尝试了更好的(对我而言)配置,我可以在配置中为不同的文件类型设置单独的目录:

location /file/ {
    rewrite . /file.php last;
}

location /file.php {
    internal;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

location ~ /film/.*\.flv$ {
    internal;
    alias /var/www/filmy;
    flv;
}

location ~ /film/.*\.mp4$ {
    internal;
    alias /var/www/filmy;
    mp4;

对http://unexisting.com/file/....../54agda0g8.flv 的请求会将我重定向到http://unexisting.com/film/54agda0g8.flv/

上帝为什么?如果您需要实时示例,请告诉我。

【问题讨论】:

    标签: php regex redirect nginx x-accel-redirect


    【解决方案1】:

    Nginx documentation 说:

    如果在正则表达式定义的位置内使用别名,则此类正则表达式应包含捕获,别名应引用这些捕获 (0.7.40)

    所以你需要在正则表达式中进行捕获,如下所示:

    location ~ ^/film/(.+\.flv)$ {
        internal;
        alias /var/www/filmy/$1;
        flv;
    }
    

    顺便说一句,你为什么要拆分这个配置?

    【讨论】:

    • 我不会拆分它,因为我有不同格式的不同位置(不同磁盘)。我将尝试捕获以查看它是否会提供文件或再次重定向。我看到了文档的那部分,但是“应该”而不是“必须”
    猜你喜欢
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 2023-03-04
    • 2020-09-11
    • 2017-04-11
    相关资源
    最近更新 更多