Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I have the following nginx config:

server {
        listen 80 default_server;
        root /var/www;
        index index.php index.html index.htm;

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

        location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
                expires 24h;
                log_not_found off;
        }

        location ~ \.php$ {
                try_files $uri =404;

                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                include fastcgi_params;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_pass 127.0.0.1:9000;
        }
}

This passes everything through /var/www/index.php when any URL is accessed.

I would like, however, for an index.php file in an arbitrary first-level subdirectory to override the root index.php file. i.e.

http://example.com/ -> /var/www/index.php
http://example.com/test -> /var/www/index.php
http://example.com/test/testing -> /var/www/index.php

but if /var/www/test/index.php exists:

http://example.com/ -> /var/www/index.php (unchanged)
http://example.com/test -> /var/www/test/index.php
http://example.com/test/testing -> /var/www/test/index.php

I've tried a number of different regexes but am stumped. Any ideas? In Apache this'd be trivial with .htaccess, but that's obviously not an option here.

share|improve this question

1 Answer 1

up vote 1 down vote accepted
location / {
    if (-e $request_filename) {
        break;
    }
    rewrite (.*/)([^\/]+) $1 last;

    try_files $uri $uri/;
}

Change last to redirect for an external redirect instead of an internal rewrite.

share|improve this answer
    
Thank you! Pity it requires an if, but it seems to work. –  ceejayoz Jul 26 '11 at 16:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.