1

I'm trying to configure my nGinx server (on a Debian Wheezy box) to serve my small PHP app. I have problems with routing.

What do I need:

/ - no PHP allowed, just .html files

/api - everything goes to /api/index.php, including /api/method1, /api/method2, etc.

That's all.

What do I have right now:

server {
    listen 3000;

    root /home/my_user/php/my_app;
    index index.html index.htm;

    # Make site accessible from http://localhost/
    server_name localhost;

    location / {
            try_files /index.html =404;
    }
    location /api {
            try_files /index.php =404;
    }

    location ~ \.php$ {
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini

            # With php5-cgi alone:
            #fastcgi_pass 127.0.0.1:9000;
            # With php5-fpm:
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            include fastcgi_params;
    }
}

What works:

/ gives me /home/my_user/php/my_app/index.html, that's OK.

/api gives me 404, that's not OK (it should go to the /api/index.php file). The same goes for /api/foo. (And yeah, the file /api/index.php exists, and is readable for everyone, just as the api/ subdirectory.)

/api/index.php gives me 404 (but a different one, I'm not sure, what's going on).

According to nginx/php tutorials I have found, everything should be OK. It isn't.

How should I configure my nginx?

1 Answer 1

3

Your config could be simplified.

server {
    listen 3000;

    root /home/my_user/php/my_app;
    index index.html index.htm;

    # Make site accessible from http://localhost/
    server_name localhost;

    location /api/ {
        try_files /api/index.php =404;

        fastcgi_pass unix:/var/run/php5-fpm.sock;
        include fastcgi_params;
    }
}

First, just serve static file is default nginx behavior, there is no need to have some special block for it. index directive is enough to make nginx search for index.html.

To map any request to /api/something to /api/index.php you should use full path as try_files construct path to file from root directive. Also fastcgi directives should be in this location because if try_files finds file it's processed in current context, i.e. inside location /api/.

There is no need for location ~ .*\.php$, because of “no PHP allowed”.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .