EDDYMENS

NGINX for Laravel projects

I have been using apache server for production and have become very comfortable with it. However last week I decided to prepare a Dockerfile for my open source project DevLess. This time I decided to go with NGINX. But as with apache, the server config file needs to be written to recognise the folder structure of the project its being used with . In Laravels own case the document root in the apache config needs to point to the public directory and remember to run a2enmod rewrite to enable .htaccess. With NGINX I was wondering what was there to watch out for? Well, it turns out the default conf file provided was good but needed a few tweaks .

        index index.html index.htm;

    server_name localhost;

    location / {
            try_files $uri $uri/ =404;
        }
    }

Default NGINX conf

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

    root /var/www/devless/public;
            index index.php index.html index.htm;

    server_name localhost;

    location / {
                  try_files $uri $uri/ /index.php$is_args$args;
            }
    }

Conf tweaked for Laravel projects

The above shows the conf file provided as the default and the edited version as well.There were three things I needed to change within the default config file to get it to work with my Laravel project.

First is the root /var/www/html; to root/var/www/devless/public; this replacement was to point the server to my project directory and for my Laravel project into the public folder.

The next was adding index.php to the list of files I wanted the server to parse before serving.

Lastly was changing how NGINX identified URIs and how to serve based on incoming requests. The default “try_files $uri $uri/ =404;” tries looking for a file based on the URI passed then a directory then finally presents you with a 404 page if no matches were found. a version of the URI that works for Laravel projects is “try_files $uri $uri/ /index.php$is_args$args;”. This tries to find a file corresponding to the URI and if not found treats it as a parameter to the index.php file found within the public directory and leaves the handling of unfound pages to your Laravel project.

Well, that’s pretty much it, to be frank, I had it easy getting started with NGINX and would spend time exploring it more. For complete tutorials on setting up the LEMP STACK check out some of the tutorials by Digital Ocean. Also, you can check out the Dockerfile for the DevLess project. Feel free to edit it for your own projects.

Happy Coding !