6

I'm migrating my server from Apache to Nginx and have this very simple .htaccess rule:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

The idea behind it is to direct every request to a front controller (index.php). I'm trying to do the same with Nginx. I used an online converter to make this Nginx location block:

location / {
    if (!-e $request_filename){
        rewrite ^(.*)$ /index.php break;
    }
}

but when I add it to my site's configuration Nginx just spits out the source code of the PHP file as a download. For reference, here's the entire configuration file:

http://pastebin.com/tyKtM1iB

I know PHP works, as if I remove the location block and make a file with <?php phpinfo(); it works correctly.

Any help would be appreciated.

2 Answers 2

13

This is how I route EVERYTHING to index.php, including sub-directory requests, HTTP args, ect.

location / {
    try_files $uri $uri/ /index.php?$args; #if doesn't exist, send it to index.php
}

location ~ \.php$ {
    include fastcgi_params;
    fastcgi_intercept_errors on;
    # By all means use a different server for the fcgi processes if you need to
    fastcgi_pass   127.0.0.1:9000;
 }

So for example, these get sent to index.php:

http://foo.bar/something/
http://foo.bar/something/?something=1

While these go directly to files

http://foo.bar/someotherphp.php
http://foo.bar/assets/someimg.jpg
Sign up to request clarification or add additional context in comments.

4 Comments

This of corse allows any existing files, such as images, or other php files to return... It routs any requests that are NOT handled to index.php.
Thanks, try_files $uri $uri/ /index.php?$args; works a treat!
+1 for using try_files instead of if
Your emphasis is wrong: This is how I route EVERYTHING to index.php, you allow existing files not to be routed. I'm looking to route everything to the front controller. you should update your answer either add such example or update as @Applehat suggested.
1

Skip end of regexp:

location / {
        index index.html index.php;
        if (!-e $request_filename) {
            rewrite ^.* /index.php break;
            fastcgi_pass 127.0.0.1:9001;
        }
}

4 Comments

Not entirely sure what's going on here. I changed my regex to match that answer but nginx still throws me the source code of PHP. Why is fastcgi_pass in that location block? Shouldn't it be under ~ \.php$?
It's from my config where we have different rules per location. Strange.
I'm not really an expert when it comes to Nginx so your guess is as good as mine. :p

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.