Take the 2-minute tour ×

totally newbie for NGINX conf file regex. I am running a PHP script that runs under NGINX web server. I am trying to let the visitor download an attached file that is different from URL. For example, if the link is:


it will actually serve the file from a different directory "media/uploaded"


based on some research, I have added something like this

location /attachment/ {      
    try_files $uri /media/uploaded/$uri;

But it's not working. My intention is not let the user browser redirect to the page that is viewing the URL, just download the file extensions like *.png, *.jpg, *.zip, etc. This scripted worked fine liked this in Apache, but it's not in Nginx.

Although it's not important, was wondering if it's also possible to let them download *.php, *.fla files without executing them for obvious security reasons. I remember using a support ticket system long time ago that allowed this too. Don't know if it's possible to pull it off from Nginx conf file.

Thank you.

share|improve this question
add comment

2 Answers

up vote 0 down vote accepted

If you want them to be like an exact mirror, easiest way is to use alias

location /attachment/ {
    alias /media/uploaded;

If you want to use try_files then you need to specify root

location ~ /attachment/(.*) {
    root /media/uploaded;
    try_files $1 =404; # or replace '=404' with any fallback rule

Your rule didn't work probably because $uri already contains /attachment so the URL that's being tested is /media/uploaded/attachment/image.jpg which doesn't exist, it could be fixed using regex like I did in the second method, but that's too much work, your case is better suited for alias

share|improve this answer
add comment

Thanks for the tips. None of them worked, but was able to add more codes to do so with alias

location  ~ ^/attachment/([^\s]+(?=\.(jpg|gif|png|zip|))\.\2) {
    alias /home/websites/public_html/media/uploaded/$1;

getting a tip from another post (forgot where it was). Thanks!

share|improve this answer
do you have a proper root in your config, on the server block level ? –  Mohammad AbuShady Oct 28 '13 at 9:16
add comment

Your Answer


