The issue of app.css and app.js resources not loading in Laravel 8 with nginx, resulting in a 404 not found error, needs to be

Although this question may appear to be a duplicate, I assure you it is different. I have thoroughly searched through Stack Overflow, Laracast, Reddit, and GitHub for a solution.

My setup includes a Laravel application on an Ubuntu VM with Nginx. The problem I am facing with my Laravel 8 app is that it fails to load the app.css and app.js files from the public/ directory. Despite running

npm install & npm run dev/prod
, I continue to encounter a 404 error - 'not found' in the Chrome console. The app.css and .js files exist in the correct directories within public/css - /js. The path generated for the resources/assets is also accurate. However, everything remains unresponsive. Various attempts to configure the server block have been unsuccessful.

If you are experiencing a similar issue even after executing npm install and run dev, utilizing the asset helper function to create the path,

<script src="{{ asset('/js/app.js') }}" defer></script>
, and
<link href="{{ asset('/css/app.css') }}" rel="stylesheet">
without any success, please refer to my answer below. It may prevent you from wasting the same amount of time I did during my lengthy search.emphasized text

Answer №1

The solution to the issue, if your configuration matches mine, is surprisingly simple.

When I set up my Laravel application, I placed it in

/home/myUsername/myLaravelAppName
and created a symlink for index.php in /var/www/myLaravelSiteName - where /var/www/myLaravelSiteName serves as the default nginx root for website hosting.

To resolve the problem, you also need to create symlinks for the /public/css/ and /public/js/ directories to /var/www/myLaravelSiteName, because the existing symlink for index.php does not include serving the css and js folders from /public/. This detail was not immediately clear to me.

Alternatively, you can symlink the entire /public/ directory to /var/wwwmyLaravelSiteName.

If this solution does not work, there may be other underlying issues that require further investigation for additional fixes. A quick but 'dirty' workaround would involve using external CDN links for bootstrap and integrating them into app.blade.php. While functional, it is not the recommended approach.

Additionally, any new custom css/js files added must be properly served with individual symlinks, rather than relying on serving the entire public/ directory collectively.

PS. Remember to create the symlink from sites-available to sites-enabled.

Here is an example of my working server block:

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;

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to including a promise.map (bluebird) within a nested promise chain

I'm currently using a chain to control flow and struggling to make promise.map within step2() wait for all generated promises to be resolved. Here's a visual representation of the flow I aim for: step1() step2() step2() ste ...

Unable to adjust the top padding of the navbar to 0 pixels

Having recently started learning HTML and CSS, I am encountering an issue with the padding on my navbar. I am unable to get it to align with the top of the site as there is a persistent space between the navbar and the top. Below is my HTML code: <!do ...

Angular2/TypeScript Coding Guidelines

I am curious about the common practices and consensus among the Angular2 community when it comes to writing reusable code in TypeScript. I have gathered some information and questions related to Angular2 that I would like to discuss. Organizing Module/A ...

clicking on a DIV element

I am trying to trigger a JavaScript function by clicking on a DIV element, but for some reason it is not working as expected. I have gone through various examples provided by the helpful people here, but still can't figure out what I'm doing wron ...

Why does my React.js application still display outdated data from my Express server even after refreshing the webpage?

I have been working on a website using React.js and Express.js, following an online example to set up the basic code. I encountered an issue where the frontend did not update when I made a minor change to the array sent by Express.js. Express - users.js f ...

Occasionally, Node.js is throwing an UnhandledPromiseRejection error, and it seems like my catch block is

Here is a snippet of my code: router.get('/myapi/someotherapi/:id', (request, response) => { console.log('api: GET /admin/myapi/someotherapi/:id'); console.log('Reject star redeem requests by id'); auth.verifyTo ...

Minimum width of Angular Material's mat-menu

I am looking to create a compact Material mat-menu using Angular 15. Below is the code I have: <mat-menu #flagMenu="matMenu"> <button mat-menu-item> <img src="assets/flags/en.png" class="flag"/> ...

Sending data from a dynamically created PHP table to a modal

In my PHP-generated table, I have: <tbody> <?php $results = DB::select()->from('users')->execute(); foreach ($results as $user) { echo "<tr id='".$user['id']."'> <input type=&bs ...

Take command of the asynchronous loop

I have two Node.js applications that serve different purposes. The first is an Express.js Server (PROGRAM1), responsible for providing the user interface and RESTful APIs. The second is a web crawler (PROGRAM2), tasked with continuously reading items, do ...

Does a DOM API exist specifically for querying comment nodes within the document?

My document contains a debugging comment that appears as follows: <!--SERVER_TRACE {...}--> Is there a method to search the DOM and access this specific node? I would prefer a vanilla JavaScript solution, without relying on any external libraries. ...

JQuery Mobile Listview Filter Not Working: Troubleshooting Tips

Recently diving into the world of jquery mobile, I've managed to successfully create a homepage and a sub-page labeled "bible_studies," complete with a dynamic list generated through AJAX. Everything seems to be functioning perfectly except for one i ...

There seems to be an issue with Node.js/Express: the page at /

Recently, I've been working on some code (specifically in app.js on the server). console.log("Server started. If you're reading this then your computer is still alive."); //Just a test command to ensure everything is functioning correctly. var ...

Failure of AJAX to transmit variable to PHP script

I am relatively new to PHP and currently working on the dashboard page of a website where an administrator can view all existing admins. Each admin's row has a button that is supposed to check their privileges, such as access to article editing and cl ...

Is it no longer possible to create custom linked Context Menus in Tabulator 5?

After using Tabulator for a few years, we have decided to switch over to Angular v13 and upgrade to the new Tabulator 5.x. In our previous implementation, we had set up a custom ContextMenu in the Table Column Definition like this: contextMenu: this.TableR ...

The content inside a Textbox cannot be clicked on. I am seeking help with implementing JavaScript to enable it to be

As a newcomer in the world of programming, I am sharing a snippet of my JavaScript and HTML code with you. I am facing an issue where I want to enable users to start typing in a text box upon clicking on the text "User Name", without deleting any existing ...

Wicked PDF - Pausing to Allow AJAX Request Completion

My challenge lies in creating a PDF using WickedPDF, where all my static HTML/CSS content loads perfectly. However, I am facing an issue with certain elements on the page which are populated through AJAX requests—they do not appear in the generated PDF. ...

Build.js.erb requesting a partial script task

Struggling to make my create action function accurately in my rails app. The following two lines work as intended: $('#pit_form').remove(); //remove form $('#new_link').show(); //show new link again They successfully remove the form ...

Is there a way to programmatically update a webpage using Javascript?

I have been attempting to set up the code in a way that the page automatically changes using setTimeout. However, I am unable to make it work. setTimeout()(page3, 500); function page3() { changepage3('automatic') } Even though my code is str ...

Obtain the total number of result entries

I'm working on a project involving JS and PHP. My goal is to call a PHP file using Ajax and have it return the count of result lines. I use echo for this: $connection = new PDO($source, $user); $query = "SELECT * FROM scores WHERE username = '" ...

Decoding a JSON object in node.js

{"__v":0,"_id":{"$oid":"55f13d34258687e0bb9e4385"},"admin":true,"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b3d6ded2c3dfd682f3d4ded2dadf9dd0dcde">[email protected]</a>","last_login":"11:25:24 AM","name ...