Nginx rewrite on specific files

nginxredirect

I have a small issue with redirecting two files from location A to location B using nginx. Those files were in a folder folderA and now I want them to be served from folderB. Unfortunately some users know the direct URL so I have to a) redirect folderA to folderB and then do the same for the relevant files.

I am using the following:

location /folderA {
    rewrite ^ http://www.example.com/folderB/ permanent;
}

and that works fine for the folder redirect. To also cater for the files I could not find anything to suit me so I created a small php script that will receive a q variable and then perform the redirects. i.e.:

location /folderA {
    try_files $uri $uri/ folderB/process.php?q=$uri&$args;
}

Unfortunately that does not work. When a request goes for the folder, the process.php is called. However when a request comes directly for a file (say abc.pdf) it doesn't get served and it gets logged in the error log.

I was under the impression that all the requests would actually end up being processed by process.php but apparently I am wrong.

Any pointers would be more than appreciated.

Thank you!

Best Answer

You can try this:

location ~* ^/folderA/.*$ {
    rewrite ^/folderA/$ http://www.example.com/folderB/ permanent;
    try_files $uri $uri/ /folderB/process.php?q=$uri&$args;
}

If it doesn't work, the error log can be of help here. Also remember that the try_files line uses $uri that includes the folder name. So the try_files in the case of abc.pdf is /foderA/abc.pdf.