Search code examples
phplinuxlaravelnginxamazon-ami

How to setup up Laravel with Nginx on AWS linux AMI


I am trying to user laravel with nginx on AWS linux ami, however when I try to access my instance public ip i get file not found. Here is what i do

sudo amazon-linux-extras install nginx1
sudo service nginx start

After this step I am sure nginx is working because I can see nginx webpage. Now I am trying to install laravel

sudo amazon-linux-extras install php7.3
sudo yum install php-xml php-mbstring
sudo service php-fpm start
sudo service nginx restart
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer
composer global require laravel/installer
export PATH=$PATH:/home/ec2-user/.config/composer/vendor/bin/
laravel new test
sudo vi /etc/nginx/nginx.conf





server {
    listen 80;
    server_name _;
    root /home/ec2-user/test/public;
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";
    index 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-fpm/www.sock;
      fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
      include fastcgi_params;
    }
    location ~ /\.(?!well-known).* {
       deny all;
    }
}
sudo chown -R apache:apache storage/
sudo chown -R apache:apache bootstrap/cache

When I try to load my page i recieve file not found.


Solution

  • You can fix this issue in 2 way:

    1. Providing a valid server name/ Domain
    2. Fixing Nginx Default IP address

    Provide valid server name

    You need to fix the server name inside your Nginx configuration you have putten the server name as _. You need to put there a valid domain name. For example:

    server_name example.com;
    

    Then create an A record of the domain pointing to the IP adress. For example:

    example.com    A    123.123.123.123
    

    Fix Nginx Default configuration

    By default, if you install Nginx the server IP takes the files from /var/www/html so you can find this issue in 2 way:

    1. Upload the files in the default path
    2. Change the Nginx default path

    Upload the files in the default path:

    • 1st delete the html folder under /var/www/
    • 2nd uload your laravel files inside /var/www/
    • 3rd rename your laravel project public folder to html
    • Now restart nginx and visit your ip

    Change Nginx Default Path

    • Open the default file
    sudo nano /etc/nginx/sites-enabled/default
    
    • Find root /var/www/html and replace the /var/www/html with your path
    • Restart nginx and then visit your IP