EDDYMENS

Last updated 2016-10-29 02:41:27

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 .

01: root /var/www/html; 02: index index.html index.htm; 03: 04: server_name localhost; 05: 06: location / { 07: try_files $uri $uri/ =404; 08: } 09: }

Default NGINX conf

01: server { 02: listen 80 default_server; 03: listen [::]:80 default_server; 04: 05: root /var/www/devless/public; 06: index index.php index.html index.htm; 07: 08: server_name localhost; 09: 10: location / { 11: try_files $uri $uri/ /index.php$is_args$args; 12: } 13: }

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 !

Here is another article you might like 😊 "Diary Of Insights: A Documentation Of My Discoveries"