Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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;

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. -> /var/www/index.php -> /var/www/index.php -> /var/www/index.php

but if /var/www/test/index.php exists: -> /var/www/index.php (unchanged) -> /var/www/test/index.php -> /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
up vote 1 down vote accepted
location / {
    if (-e $request_filename) {
    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

A solution based on h0tw1r3's, but without an if:

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

location @pop {
        rewrite (.*/)([^\/]+/?) $1 last;
share|improve this answer

Your Answer


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.