Fix for Nginx Bug Using Alias and Try_files

One of the projects I work on uses a combination of Angular and Laravel. Our Angular-based single page application consumes our restful API written in Laravel. We came across a bug that we had to find a solution for.

To help deal with cross-site requests we decided to put the Laravel code base under the alias /api. For example, our website lives at and our API lives at When trying this on our Nginx server we ran into a problem, so I thought I would share the solution.

The Problem

In the past we were using Apache for our web server and running an alias seemed to be no problem. However, recently we had moved to Nginx and during this project stumbled across a bug with Nginx’s handling of aliases. Where Apache would use if statements to look for existing files and then fall back to the index, Nginx uses a directive called try_files. An example of when to use try_files if you are using an application where one file is the main driver. A very popular example in this would be a blog running WordPress because the index.php is the main driver for the application.

Apache Example

Nginx Example

What both of these pieces of code do is tell the web server that if a file or directory exists that matches the request use it to serve that request, however if there is no match then fall back and serve index.php.

This solution works fine for both, but the problem arises when trying to use aliases and Nginx. Nginx currently has a reported bug for the use of aliases with try_files.

The Solution

I spent a good deal of time looking for a solution to this problem, but all I found was others with the same problem. There was a question on the Laracast forum with someone who had the same problem. Finally I figured out that I could use a combination of the old if statements and the new Nginx configuration to get the desired outcome. The configuration used to fix this problem is listed below. By putting the location block in your Nginx configuration file you will be able to achieve the results as if the try_files and alias were working together.

Nginx Solution

Although this solution uses if statements that some have considered bad form it functions as a solution to the problem until a true fix is released.