1

Nginx 1.10.3 Ubuntu, standard apt installation. index index.php; located outside server block.

I need:

  • http://example.com/test/1 pointing to /var/www/example.com/test/1
  • http://example.com/test/2 pointing to /var/www/example.com/test/2

..and so on.

Because I will create too many test, I need a wildcard for try_files. Currently I'm doing without wildcard:

server {
    server_name example.com;
    root   /var/www/example.com;
    location /test/1/ {
        try_files $uri $uri/ /test/1/index.php?$args;
    }
    location /test/2/ {
        try_files $uri $uri/ /test/2/index.php?$args;
    }
    location ~ \.php$ {
        ...
}

Out of many recommendations, none of them works.

Plain PHP running fine. WordPress & Laravel gave "File not found":

server {
    server_name example.com;
    location ~ ^/test/(?<content>.+)$ {
        root   /var/www/example.com/test/$content;
        try_files $uri $uri/ /index.php?$args;
    }
    location ~ \.php$ {
        ...
}

File not found:

server {
    server_name example.com;
    location ~ ^/test/(?<content>[^/]+) {
        root   /var/www/example.com/test/$content;
        try_files $uri $uri/ /index.php?$args;
    }
    location ~ \.php$ {
        ...
}

On all attempts below, It download the PHP file instead of run PHP:

server {
    server_name example.com;
    root   /var/www/example.com;
    location ~ /(?<content>[^/]+) {
        try_files $uri $uri/ /$content/index.php?$args;
    }
    location ~ \.php$ {
        ...
}

server {
    server_name example.com;
    root   /var/www/example.com;
    location ~ /(.*)/ {
        try_files $uri $uri/ /$1/index.php?$args;
    }
    location ~ \.php$ {
        ...
}

server {
    server_name example.com;
    root   /var/www/example.com;
    location ~ /test/(?<content>[^/]+) {
        try_files $uri $uri/ /test/$content/index.php?$args;
    }
    location ~ \.php$ {
        ...
}

server {
    server_name example.com;
    root   /var/www/example.com;
    location ~ /test/(?<content>.+) {
        try_files $uri $uri/ /test/$content/index.php?$args;
    }
    location ~ \.php$ {
        ...
}

If can, I willing to give $10 for the right answer

Isak Pontus
  • 47
  • 1
  • 9

1 Answers1

3

The regular expression location blocks are evaluated in order, so the .php block must be placed before the /test/... block, otherwise the .php files under /test/ will be downloaded instead of being executed. See this document for details.

Your best version was second from last. The regular expression extracts just the path element following the /test/ prefix.

Just reverse the location blocks. For example:

server {
    server_name example.com;
    root   /var/www/example.com;
    location ~ \.php$ {
        ...
    }
    location ~ /test/(?<content>[^/]+) {
        try_files $uri $uri/ /test/$content/index.php?$args;
    }
}
Richard Smith
  • 12,834
  • 2
  • 21
  • 29