Nginx yet another rewrite or internal redirection cycle

nginxPHPphp-fpm

Yet another redirection cycle, yes.

Have looked at other questions, but just can't seem to get it to work.

server {
    listen          80;
    server_name     localhost;

    charset         utf-8;

    access_log      /srv/http/localhost/log/access.log;
    error_log       /srv/http/localhost/log/error.log;

    location / {
        root        /srv/http/localhost/www;
        index       index.html index.php;
    }

    # prevent access to hidden files
    location ~ /\. {
        access_log      off;
        log_not_found   off;
        deny            all;
    }

    # do not log assets
    location ~* \.(jpg|jpeg|gif|png|css|js|ico|xml)$ {
        access_log      off;
        log_not_found   off;
        expires         360d;
    }

    # pass the PHP scripts to PHP-FPM socket
    location ~* \.php$ {
        try_files       $uri /index.php;
        fastcgi_pass    unix:/var/run/php-fpm/php-fpm.sock;
        include         fastcgi_params;
    }
}

This is my full server{} block for main host, that results in:

2012/07/29 00:34:52 [error] 14810#0: *10 rewrite or internal
redirection cycle while internally redirecting to "/index.php",
client: xx.xx.xx.xx, server: localhost, request: "GET /phpinfo.php
HTTP/1.1", host: "xx.xx"

When accessing <anything>.php – index.php, phpinfo.php, i.php etc.

This results in 500 Internal Server Error, when I experimented with try_files, I ended up with 404 from time to time, but mainly the redirection cycle.

What is the problem here?

Best Answer

You've put try_files in the wrong location. It should not be in the location where you send requests upstream to php-fpm, but in your location /.

You also have root in the wrong place. It should be within the server block, not within the location / block.

Finally, you need a fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_filename; in the location ~* \.php$ block.