Nginx – How to Redirect URL Containing ‘PHP’

nginxredirect

Recently I changed my website that was used PHP/Apache to Django/Nginx. I would like to give a http response 301 and redirect to my main page all requests that contain ".php" in url.

Example:

example.com/**?page=show.php&id=2748**

example.com/**index.php?page=show_page.php&id=2748**

The ".php" can be in any position in the URL.

I tried:

location ~ \.php {
        rewrite ^/(.*) http://www.example.com permanent;
    }   

But, of course, it just work when have .php in the end. Can anybody give me a clue?

UPDATED:
If I use this solution:

            if ($request_uri ~* "php") {
           rewrite ^/(.*) http://www.example.com permanent;
        }   

I get the following error in the log:

[29/Aug/2011:13:30:25 -0300] "GET /?page=show_page.php&id=2748 HTTP/1.0" 301 184 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0"
[29/Aug/2011:13:30:26 -0300] "GET /?page=show_page.php&id=2748 HTTP/1.0" 301 184 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0"
[29/Aug/2011:13:30:26 -0300] "GET /?page=show_page.php&id=2748 HTTP/1.0" 301 184 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0"
[29/Aug/2011:13:30:27 -0300] "GET /?page=show_page.php&id=2748 HTTP/1.0" 301 184 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0"
[29/Aug/2011:13:30:27 -0300] "GET /?page=show_page.php&id=2748 HTTP/1.0" 301 184 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0"
[29/Aug/2011:13:30:28 -0300] "GET /?page=show_page.php&id=2748 HTTP/1.0" 301 184 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0"
[29/Aug/2011:13:30:28 -0300] "GET /?page=show_page.php&id=2748 HTTP/1.0" 301 184 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0"

Why it tries to redirect too many times?

UPDATED:

I Tried:

  if ($request_uri ~ .*.php.*) {
        rewrite ^/ http://www.example.com permanent;
    }

its working, but when the URL starts with "?" I get same error. So, 50% of the problem was solved…

SOLUTION:

        if ($request_uri ~ .*.php.*) {
            #return 410;
        rewrite ^ http://$host? permanent;

Best Answer

The problem was in the rewrite.

I changed rewrite to return code 410, I think that I would do that instead return return 301 (permanent).

So, here is the code:

if ($request_uri ~ .*.php.*) {
        return 410;
}

Now, nginx will return 4010 for all pages that that contain ".php" in anywhere in URL. My django site can live in peace now ;-)