nginx “try_files” directive is not allowed here

By | January 12, 2018
Questions:

What I want to achieve is pretty simple :

If the subdomain starts with admin, try to serve directly from controller admin.php for all other cases, try to serve files with site.php.

Note that I don’t know domain names as a lot of domains are pointing to us.
What I tried so far:

server {
    listen 8080;
    root /path/to/current/web;

    location / {
        if ($http_host ~ "^admin") {
            try_files $uri @rewriteadmin;
        }
        if ($http_host !~ "^admin") {
            try_files $uri @rewriteapp;
        }
    } 

    location @rewriteapp {
        rewrite ^(.*)$ /site.php/$1 last;
    }

    location @rewriteadmin {
        rewrite ^(.*)$ /admin.php/$1 last;
    }
    ...
 }

Of course this setup doesn’t work and gives me : [emerg] "try_files" directive is not allowed here.

What’s the best practice to achieve that please ?

Answers:

You could use regexps in server_name. So it’s better to use two server blocks.

server {
    listen 8080 default_server;
    root /path/to/current/web;

    location / {
        try_files $uri @rewriteapp;
    } 

    location @rewriteapp {
        rewrite ^(.*)$ /site.php/$1 last;
    }

    ...
}

server {
    listen 8080;
    server_name ~^admin;
    # or better, if they all starts with "admin." token
    # server_name admin.*;
    root /path/to/current/web;

    location / {
        try_files $uri @rewriteadmin;
    } 

    location @rewriteadmin {
        rewrite ^(.*)$ /admin.php/$1 last;
    }

    ...
}

Leave a Reply

Your email address will not be published. Required fields are marked *