使用Nginx限制对MVC应用程序的一个控制器的访问

我有一个MVC应用程序,其中一个控制器只能从几个ips访问(这个控制器是一个oauth令牌callback陷阱 – 对于google / fb api令牌)。 我的conf看起来像这样:

geo $oauth { default 0; 87.240.156.0/24 1; 87.240.131.0/24 1; } server { listen 80; server_name some.server.name.tld default_server; root /home/user/path; index index.php; location /oauth { deny all; if ($oauth) { rewrite ^(.*)$ /index.php last; } } location / { if ($request_filename !~ "\.(phtml|html|htm|jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js|xlsx)$") { rewrite ^(.*)$ /index.php last; break; } } location ~ \.php$ { fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; include fastcgi_params; } } 

它有效,但看起来不正确。

以下对我来说似乎很合理:

  location /oauth { allow 87.240.156.0/24; deny all; rewrite ^(.*)$ /index.php last; } 

但是这样一直重写,允许和拒绝指令被忽略。 我不明白为什么…

它总是重写的原因是因为重写指令在重写阶段被评估,重写阶段在访问阶段之前,评估允许和拒绝。 他们在文件中出现的顺序并不重要。 您可以通过以下两种方式来解决这个问题:要么不要在location / oauth中使用rewrite将请求发送给前端控制器,要么在重写阶段处理源ip。 你已经在你的工作configuration中做了后者,但是可以做得更清楚些:

 geo $oauth_denied { default 1; 87.240.156.0/24 0; 87.240.131.0/24 0; } server { ... location /oauth { if ($oauth_denied) { return 403; } rewrite ^ /index.php last; } ... } 

要么:

 server { ... # include at server level so they're inherited by locations include fastcgi_params; location /oauth { allow 87.240.156.0/24; deny all; # try_files will change $uri so all the params work try_files /index.php =404; fastcgi_pass unix:/var/run/php5-fpm.sock; } ... }