Nginx configuration – redirect if file exists

nginxPHPrewrite

I'm transitioning a php application written by someone else from apache to nginx.

the developer has this in .htaccess

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-s
    RewriteRule ^(.*)$ api.php?rquest=$1 [QSA,NC,L]

    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^(.*)$ api.php [QSA,NC,L]

    RewriteCond %{REQUEST_FILENAME} -s
    RewriteRule ^(.*)$ api.php [QSA,NC,L]
</IfModule>

I read this briefly as
"if the file/directory does not exist, rewrite the request to be for api.php?rquest=$uri"
"if the file/directory does exist, rewrite the request to be for api.php"

I tried replicating this in nginx but running into issue. i created a location directive with

location / {
    # if the file or folder doesn't exist add it as arguments to api.php
    try_files $uri $uri/ /api.php?rquest=$uri&$args;

    index api.php;
}

and what i want to do is just direct to a static index.html page somewhere if the file/directory does exist.

I tried server level "if" statement with rewrite

if (-e $request_filename){
    rewrite ^(.*)$ /api.php break;
}

but this breaks other valid location directives.

How do I accomplish this:
if the file/directory does exist, redirect to a static html page

—————- Update —————

I finally ended up with something like

server {
    ...

    root  /home/ballegroplayer/api/public;
    index index.php index.html index.htm;

    try_files $uri $uri/ /api.php?rquest=$uri&$args;

    if (-e $request_filename){
        rewrite ^(.*)$ /api.php last;
    }

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

Ultimately, in the "if" statement we can't redirect to a static file because after the "try_files" directive succeeds we get redirected to api.php which does exist and would cause the "if" statement to be triggered and we would always get the static html page.

Best Answer

I think using last instead of break solves the issue, since that makes nginx not to re-process the locations with the rewritten URL path.