拒绝后如何防止重写

时间:2017-03-16 11:03:24

标签: nginx nginx-location

我的网站内有" /目录/",以及网站内的特殊变体" / directory / subdirectory /"只应通过几个特定的​​IP地址访问。但是,子目录是一个虚拟URL,网站代码仍在父目录中,名为" directory"在这个例子中。所以我需要重写。

这是我当前nginx配置文件的相关部分:

location /directory {
    # here are various rewrites for my website

    location /directory/subdirectory/ {
        allow 10.0.0.0/8; # example range of IP addresses allowed 
        deny all; # disable access for others
        rewrite ^/directory/subdirectory/(.*)$ /directory/$1 last; # the website location is still in the parent folder but the PHP code knows this specific version is to be used when the user surfs into subdirectory, which is why there is this rewrite
    }

    try_files $uri $uri/ /directory/index.php?q=$uri&$args;
}

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    include fastcgi.conf;
    fastcgi_read_timeout 43200; 
}

我面临的问题:我不知道如何拒绝所有"拒绝所有"命中。如果您正在浏览子目录,则无论您的IP是否被其上方的指令允许,重写始终都会执行。因此,有人使用不允许的IP地址浏览子目录的人可以看到子目录中的网站,这当然不是我想要的。如果我注释掉重写,那么allow / deny指令就可以正常工作。

那么:如果访问者没有被拒绝,我怎么能指定这个重写只能被执行? 尝试添加" error_page 403 /403.html;" " deny all之后到那个位置;"指令,但它只更改403页面(并且只能在子目录中注释重写规则时再次看到)。已经在网上搜索了几天已经有各种搜索条件来实现这一点,并且一直在摆弄配置的变化,但无济于事。

另外:"拒绝所有"一旦我浏览到子目录中的URL,以" .php"结尾,我就不再工作了。我认为这是因为"位置〜.php $"指令,由于某种原因优先于上面的嵌套位置指令。我可以通过这样做来解决这个问题:

location ^~ /directory/subdirectory/ {
    allow 10.0.0.0/8; # example range of IP addresses allowed 
    deny all; # disable access for others
    rewrite ^/directory/subdirectory/(.*)$ /directory/$1 last;
}

location /directory {
    # here are various rewrites for my website

    try_files $uri $uri/ /directory/index.php?q=$uri&$args;
}

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    include fastcgi.conf;
    fastcgi_read_timeout 43200; 
}

现在"位置^〜/ directory /子目录/"指令优先于"位置〜.php $"使"拒绝所有"的指令工作,但我不知道这是否是要走的路,因为它似乎并不是最清楚的阅读"解决方案,因为我从"目录/"该位置块之外的位置。而且,这仍然没有解决我的主要问题(只有#34;重写^ /目录/子目录/(.*)$ /目录/ $ 1最后;"执行允许的IP地址和不是那些被拒绝所有"否则被拒绝的人。

谢谢。

1 个答案:

答案 0 :(得分:1)

您面临的问题与nginx处理其指令的优先级/顺序有关。可以找到详细解释here (hats off to the author!)

  

在执行顺序中,阶段是后读,服务器重写,   find-config,rewrite,post-rewrite,preaccess,access,post-access,   尝试文件,内容,最后记录

因为"重写"来之前"访问","重写"首先处理指令。

因为"如果"在"重写" -phase处理,可以写:

location ~ \.php$ {
 if ($remote_addr != "172.17.0.1") {
  return 403;
 }
 rewrite ^ /your-redirect last;
}