Levyce
Levyce

Reputation: 125

Nginx with Slim framework - php files getting downloaded

I'm trying to setup a simple REST api for a database connection and have decided to do so by using nginx and the Slim framework. Installed both (slim locally in a project directory via the Composer dependency manager /home/some_user/slim_project/).

After that I tried to implement the Slim code-example and followed a couple guides doing so, but with all my attempts I ended up failing. Either the php-file gets downloaded or i simply get the Slim "Page not found" page.

The project is running on a raspberry pi with a dynamic DNS configured.

My structure and code looks like this:

/home/some_user/slim_project/public/index.php

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

require '../vendor/autoload.php';

$app = new \Slim\App;
$app->get('/hello/{name}', function (Request $request, Response $response, 
array $args) {
    $name = $args['name'];
    $response->getBody()->write("Hello, $name");

    return $response;
});
$app->run();

and the nginx config:

/etc/nginx/sites-enabled/default

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        root /home/some_user/slim_test/public/;

        server_name mySlimTest1.ddns.net;

        location / {
                if (!-e $request_filename){
                        rewrite ^(.*)$ /index.php break;
                }
                try_files $uri $uri/ =404;
        }

        location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        }
}

Whatever I try, all that happens is the php-file getting downloaded or in some cases I get a 404 when I add the exemplary '/hello/Hans' to the end of the server url.

I followed this tutorial for example: https://www.slimframework.com/docs/v3/tutorial/first-app.html
I am clearly missing something here. Any help would be appreciated.

Upvotes: 1

Views: 975

Answers (1)

Richard Smith
Richard Smith

Reputation: 49702

Your rewrite...break causes the new URI to be processed in the same location, you should use rewrite...last when internally redirecting to a .php URI from a different location block. See this document for details.

However, your if block performs a similar function to try_files. The same functionality can be achieved with the following:

location / {
    try_files $uri $uri/ /index.php$is_args$args;
}

Upvotes: 1

Related Questions