Nginx redirect all request that does not match a file to a php file

Posted by cyrbil on Server Fault See other posts from Server Fault or by cyrbil
Published on 2013-11-06T09:14:35Z Indexed on 2013/11/06 9:55 UTC
Read the original article Hit count: 209

I'm trying to get all request to: http://mydomain.com/downloads/* redirect to http://mydomain.com/downloads/index.php except if the requested file exist in /downloads/

ex:

  • http://mydomain.com/downloads => /downloads/index.php
  • http://mydomain.com/downloads/unknowfile => /downloads/index.php
  • http://mydomain.com/downloads/existingfile => /downloads/existingfile

My current problem is I have either the redirection to php working but static files not served or the opposite.

Here is my current vhost conf: (which redirect fine but static files are send to php and fail)

server {
    listen   80; ## listen for ipv4; this line is default and implied
    server_name domain.com;
    root /data/www;
    index index.php index.html;

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

    error_page 404 /404.html;

    # redirect server error pages to the static page /50x.html
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/www;
    }

    location ^~ /downloads {
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_index index.php;
        include fastcgi_params;
        try_files $uri @downloads;
    }

    location @downloads {
        rewrite ^ /downloads/index.php;
    }

    # pass the PHP scripts to FastCGI server
    #
    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }
}

Precision: static files are symlinks created by /downloads/index.php

Thank you for your help.

© Server Fault or respective owner

Related posts about nginx

Related posts about redirect