Nginx – Serve Plain File if Exists Else Serve /index.php

nginxrewrite

I want Nginx to serve any requests for static files on its own, but if the file doesn't exist, then serve index.php which will handle it all

Currently my configuration looks like this,

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

root /home/www/example.com/htdocs;

index index.php;

server_name www.example.com;


location ~* ^[^\?\&]+\.(html|jpg|jpeg|json|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js|svg|woff|ttf)$ {
    # First attempt to serve request as file, then
    # as directory, then fall back to index.php
    try_files $uri $uri/ /index.php;
    #try_files /favicon.ico =404;
}


location / {
    add_header X-Is-PHP true;
            try_files /index.php =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            # With php5-fpm:
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            include fastcgi.conf;
    }


}

This is as close as I can get, it serves any request for static files, and if it doesn't exist, serves index.php as a plaintext file. How can I get index.php passed on to the PHP interpreter?

Best Answer

try this

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

root /home/www/example.com/htdocs;

index index.php;

server_name www.example.com;


location ~* ^[^\?\&]+\.(html|jpg|jpeg|json|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js|svg|woff|ttf)$ {
    # First attempt to serve request as file, then
    # as directory, then fall back to index.php
    try_files $uri $uri/ /index.php;
    #try_files /favicon.ico =404;
}

error_page 404 /index.php;

location ~ \.php$ {
            add_header X-Is-PHP true;
            #try_files $uri =404;
            try_files /index.php =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            # With php5-fpm:
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            include fastcgi.conf;
    }


}

changes

1) Added error_page 404 /index.php; so that all the requests not found on the server are redirected to index.php

2) Added "~ .php$" to location attribute.

3)If u want other PHP files to be interpreted as well, uncomment the line "#try_files $uri =404;" and comment the line "try_files /index.php =404;"