cannatown
cannatown

Reputation: 985

nginx - how to use 'try_files' and an 'index' statement in the same directory?

Both landing.php and all the other pages of my site are in the same directory. I want to be able to access both, however if I have a try_files statement as well as an index statement, I get a 404 error when accessing the index page.

Is there a way to achieve this without conflicting either?

Here's my configuration file:

server {
    listen 80;
    access_log /var/www/mysite.com/logs/access.log;
    error_log /var/www/mysite.com/logs/error.log;
    root /var/www/mysite.com/public_html/mysite/public/_main;
    server_name www.mysite.com mysite.com;

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

    location ~ \.php$ {
            try_files $uri =404;
            include /etc/nginx/fastcgi_params;
            fastcgi_pass unix:/var/run/php-fastcgi/php-fastcgi.socket;
            fastcgi_index landing.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

Upvotes: 1

Views: 2657

Answers (2)

cannatown
cannatown

Reputation: 985

I finally worked out how to do this. What you need is two location blocks, like this:

location = / {
     index landing.php;
}

location / {
     try_files $uri $uri.php?$query_string;
}

What this does is use try_files for any other page such as www.site.com/somepage; however if the URL is www.site.com, it will fetch the index page.

Upvotes: 2

avichalp
avichalp

Reputation: 1120

Try the following config it worked for me:

server {
    root /path/to/root;
    index index.html index.htm;

    server_name subdomain.domain.com;

    location / {
        try_files $uri $uri/ /index.html;
        auth_basic "Restricted";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }

    location /doc/ {
        alias /usr/share/doc/;
        autoindex on;
    }
}

Upvotes: 0

Related Questions