Nginx rewrite downloads php instead of running it

JFallz asked:

I have the following code to redirect users visiting login.php to another page:

http {
....
geo $bad_user {
  default 0;
  1.2.3.4/32 1;
  4.3.2.1/32 1;
 }

server {
....
location = /login.php {
if ($bad_user) {
rewrite ^ http://example.com/foo.php;
      }
  }
 }
}

It makes the login.php file downloaded instead of redirecting users to the other page. All other php files are working except that file (login.php). And if I removed the above code it works fine, but it won’t make the redirection.

I tried the following:

      rewrite ^ http://example.com/foo.php last;

&

      rewrite ^ http://example.com/foo.php$1 last;

but none of them worked for me. I also restarted the whole server but it didn’t work.

Any suggestions please?

My answer:


Don’t use a separate location. In your configuration there are no fastcgi directives to handle the case where the user is not a bad_user, thus nginx treats it as a static file and serves it directly.

Instead, put the check in your existing location ~ .php$ block, and then check for login.php there.

For example:

location ~ .php$ {
    if ($bad_user) {
        rewrite ^/login.php http://example.com/foo.php;
    }
    #....everything else

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.