Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx: Redirect all non-existing requests to index.php

I'm in the midst of migrating over to Nginx, from Apache.

I'm currently using a custom content management solution that utilizes the SERVER['request_uri'] to handle routing.

What I am trying to do is redirect all non-existing files & directory requests to /index.php, and not update the clients uri. However, when a file does exist, I want to return that instead.

An example url would be: localhost/content/page/1 <- Should populate $_SERVER['request_uri'] to be /content/page/1 Or localhost/public/script/exists.js <- Should be returned as an actual file.

like image 645
Mark LeBlanc Avatar asked Dec 22 '12 05:12

Mark LeBlanc


1 Answers

You need to add a location / block or update your current location / block in your nginx vhost file.

This will redirect all request to the index.php if the file or directory is not found:

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

This goes inside your server directive, for more information visit http://wiki.nginx.org/HttpCoreModule

After you modify your vhost file you need to restart nginx

Note: The try_files directive for server blocks was added in 0.7.44

like image 135
PhearOfRayne Avatar answered Sep 21 '22 09:09

PhearOfRayne