Laravel 8 + nginx - app.css和app.js资源从公共/未加载- 404未找到



这似乎是一个重复的问题,但它是不同的。相信我,我研究了整个堆栈,laracast, reddit和github为这个

我在nginxubuntu VM上有一个Laravel应用程序。我的问题是我的Laravel 8应用程序是,它没有加载app.cssapp.js文件从public/。我已经运行了npm install & npm run dev/prod,但我仍然得到了404错误-在chrome中没有找到控制台。所以我的app.css and .js在我的public/css - /js文件夹。路径也被正确地生成资源/资产。还是不行。我已经尝试了几个server block配置,没有成功。

如果你有同样的问题,并尝试过npm install and run dev,使用asset辅助函数来生成path<script src="{{ asset('/js/app.js') }}" defer></script><link href="{{ asset('/css/app.css') }}" rel="stylesheet">,但仍然没有看看下面我的答案,它可能会为你节省我花的一周时间搜索。*强调文本

如果您的配置与我相同,那么解决方案非常简单。

我安装了我的Laravel应用程序在/home/myUsername/myLaravelAppName与index.php符号链接在/var/www/myLaravelSiteName-/var/www/myLaravelSiteName是默认的nginx根服务器的网站-如你所知。

解决方案:为每个/public/css/和/public/js/目录做一个符号链接到/var/www/myLaravelSiteName,因为index.php的符号链接不提供css和js文件夹from/public/.显然这对我来说不是那么明显。

或者您可以将整个/public/目录符号链接到/var/wwwmyLaravelSiteName .

如果这仍然不起作用,你可能有其他问题,所以继续搜索,因为有其他的修复。一个快速但"肮脏"的修复将使用在线CDN链接从bootstrap和添加它们在app.blade.php。它可以工作,但不推荐。

此外,您添加的任何新的自定义css/js文件都必须加载,因此首选正确的功能方式。这些必须有符号链接,如果单独服务,而不是与整个公共/目录。

p。不要忘记将来自sites-available的符号链接设置为启用了sites-enabled。

我的工作服务器块:

server {
listen 80;
listen [::]:80;

root /var/www/laravel;

add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
charset utf-8;
index index.php index.html index.htm ;
server_name laravel www.laravel;
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt  { access_log off; log_not_found off; }

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

include /etc/nginx/fastcgi_params;
fastcgi_split_path_info ^(.+.php)(/.+)$;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
try_files $uri = 404;
}
location ~* .(jpg|jpeg|png|gif|css|js|ico|html)$ {
access_log off;
expires max;
log_not_found off;
}

location ~/.ht {
deny all;
}
sendfile off;
}

最新更新