sf_tristanb
sf_tristanb

Reputation: 8855

nginx "try_files" directive is not allowed here

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 ?

Upvotes: 3

Views: 7430

Answers (2)

ᴍᴇʜᴏᴠ
ᴍᴇʜᴏᴠ

Reputation: 5256

Quick answer: try_files needs to be inside a location.

Quick fix:

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

Works for my CakePHP v 3.x

Upvotes: 2

Alexey Ten
Alexey Ten

Reputation: 14354

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;
    }

    ...
}

Upvotes: 2

Related Questions