Search code examples
laravelhttpnginxftpwebserver

HTTPServer only on a certain directory of project - NGINX


Goal

My goal is to see something like this, when I visit a certain URL of my app :

enter image description here


Try

location /backup {
    autoindex on;
    index index.html; 
    root /home/app/public/backup;
}

Result

enter image description here


Config

My entire vi /etc/nginx/sites-available/default

server {

    listen 80 default_server;
    server_name default;
    root /home/app/public;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    index index.html index.htm index.php;

    charset utf-8;

    location /backup {
        autoindex on;
        index index.html;
        root /home/app/public/backup;
    }


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

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    access_log off;
    error_log  /var/log/nginx/default-error.log error;

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }
}

Solution

  • With your configuration, nginx is trying to locate /home/app/public/backup/backup path, hence 404.

    These 3 solutions will work for you

    # remove root directive (recommended in your case)
    location /backup {
        autoindex on;
        index index.html;
        #root /home/app/public/backup;
    }
    
    # set root to public (redundant since already done)
    location /backup {
        autoindex on;
        index index.html;
        root /home/app/public;
    }
    
    # replace root with alias
    location /backup {
        autoindex on;
        index index.html;
        alias /home/app/public/backup/;
    }
    

    For more information check how root and alias work, you can also read how nginx handles user requests