简体   繁体   中英

Laravel assets and routes returning 403 after deploying on production server using nginx

The routes and assets are loading properly on local server. However, after I deployed on production server using nginx, only the root url is working which is http://calculator.example.com . But all the assets are returning 403. Also when I try to access any routes for eg: http://calculator.example.com/page-1/ it is also returning 403.

Nginx config:

server {
    listen 80;
    server_name calculator.example.com;
    root /var/www/html/calculator/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    index index.html index.htm index.php;

    charset utf-8;

    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; }

    error_page 404 /index.php;

    location ~ .php$ {
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /.(?!well-known).* {
        deny all;
    }
}

First, you need check if requests have been passed to app. if 403 be returned in nginx, i think issue is user run nginx not have permission to access or execute code. if 403 be returned in php app, please debug normally.

This issue got resolved after I removed the deny all for other location:

location ~ /.(?!well-known).* {
    deny all;
}

If you have directory indexing off, and is having this problem, it's probably because the try_files you are using has a directory option:

location / {
    try_files $uri $uri/ /index.php?$query_string;
}                 ^ that is the issue

Remove it and it should work:

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

Why this happens

TL;DR: This is caused because nginx will try to index the directory, and be blocked by itself. Throwing the error mentioned by OP.

try_files $uri $uri/ means, from the root directory, try the file pointed by the uri , if that does not exists, try a directory instead (hence the / ). When nginx access a directory, it tries to index it and return the list of files inside it to the browser/client, however by default directory indexing is disabled, and so it returns the error "Nginx 403 error: directory index of [folder] is forbidden".

Directory indexing is controlled by the autoindex option: https://nginx.org/en/docs/http/ngx_http_autoindex_module.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM