Nginx rewrite downloads php instead of running it

Mina Hafzalla asked:

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

http {
geo $bad_user {
  default 0; 1; 1;

server {
location = /login.php {
if ($bad_user) {
rewrite ^;

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 ^ last;


      rewrite ^$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;
    #....everything else

View the full question and any other answers on Server Fault.

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