Hello friends! Whenever you have installed Magento 2 in your local machine it very common that you might encounter this issue: CSS and JS not loading in Magento 2. Today we will solve the core problem on this issue that might be causing this issue.
This is what a typical Magento 2 homepage would look like after installation and without the CSS and JS loading:
This issue is most probably caused when the files are not generated properly and this can be resolved by generating the static files using the following command:
php bin/magento setup:static-content:deploy
After generating the static files, you can clear the cache using the cache flush commands:
php bin/magento cache:flush
Once the Magento static files generation command and the cache flush commands are executed, navigate to the <Magento Root Directory>/pub/static folder and make sure the frontend, backend folders are created and there should be a text file named as deployed_version.txt.
The frontend folder in the pub/static folder contains all the CSS and JS related to the frontend (store front) of the website and the backend folder contains all the CSS and JS related to the admin panel of the Magento website.
If these files are generated and still the site is not loading the CSS and JS of the website, then it is mostly due to the redirection issue. This can be confirmed by opening the source view of the webpage and clicking on the CSS file link that would be loaded:
Upon clicking this link URL, the browser will attempt to load the CSS file in a new tab in the browser. If it displays a 404 error like the below screenshot, then it is very clear that the issue is because of the URL rewrites not working:
To fix this, the mod_rewrite module needs to be enabled in the Apache server. This module is required so that the CSS and JS files are accessed from the pub/static folder by URL redirection based on the value in the deployed version.
sudo a2enmod rewrite
sudo service apache2 restart
To activate this module, navigate to /etc/apache2 and open the apache2.conf file to update the value under <Directory /var/www/> elements from AllowOverride Null to AllowOverride All and Require all denied to Require all granted like in the below screen:
This is how your entry in the apache2.conf file would be after making the changes:
<Directory /var/www/> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory>
After change these values restart the Apache 2 server:
sudo systemctl restart apache2
This should get your issue resolved.