Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I configure nginx to load try_files from a different folder?

Tags:

nginx

I need some help configuring nginx to load files from a different folder. Here is my config:

index index.php;

server {
    server_name domain.com;
    root /www/domain.com/www/;

    location / {
            try_files $uri $uri/ /php_www/index.php;
    }

    location ~ \.php$ {
            try_files $uri =404;
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index /php_www/index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param PATH_INFO $fastcgi_script_name;
            include /etc/nginx/fastcgi_params;
    }

    error_page  404  /404.html;

    error_log /var/log/nginx/error.log;

}

The problem is that /php_www/ is not located inside the root defined in nginx.

I have 4 different folders that I need to do this with, here is what my folder structure looks like:

/www/domain.com/www/
/www/domain.com/php_www/
/www/domain.com/content1/
/www/domain.com/content2/

What I'm trying to do is when a visitor goes to domain.com/page1/content1/ I want to load content from the content1 folder, for example. The reason for this is I have several git projects with separate repos...this will enable me to push certain areas of the website to production, without effecting anything else. I'd like to not have all my files/content accessible in the /www folder too, so urls can't be brute force attacked, looking for content.

Hopefully this makes sense!

Working solution (pulled from this comment)

location ^~ / { 
    root /www/domain.com/php_www/; 
    try_files $uri $uri/ /index.php; 
    location ~* \.(?:php|html)$ { 
        try_files $uri =404; 
        fastcgi_pass 127.0.0.1:9000; 
        include /etc/nginx/fastcgi_params; 
    }
}
like image 744
tvpmb Avatar asked Jul 27 '12 00:07

tvpmb


People also ask

Where do I put html files in nginx?

By default Nginx Web server default location is at /usr/share/nginx/html which is located on the default file system of the Linux.

Which directory serves static content by default nginx?

Root Directory and Index Files.

What does Try_files do in nginx?

The try_files directive exists for an amazing reason: It tries files in a specific order. NGINX can first try to serve the static content, and if it can't, it moves on. This means PHP doesn't get involved at all.


1 Answers

You can use the root directive inside location.

like image 80
VBart Avatar answered Nov 16 '22 01:11

VBart