Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect URL to PHP only if file does not exist with Nginx

Tags:

php

nginx

I am trying to get Nginx to rewrite URL space ./data/(.+).png to serveImage.php?guid=$1

server {
    server_name my.server;
    listen 80;
    listen 127.0.0.1:80;
    root /var/www/my.server;
    index index.html;

    location / {
        try_files $uri $uri/ index.html;
        rewrite ^/data/(.+).png serveImage.php?guid=$1 last;
    }

    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param HTTPS off;
    }
}

What am I doing wrong? serveImage.php does exist in the document root.

like image 809
adrenalin Avatar asked Oct 20 '13 19:10

adrenalin


2 Answers

Rewriting did not seem to work as planned (nothing that appeared to access.log or error.log gave even a hint that the rule was even caught). I made a more generic router that might fit better the other yet unknown needs as well.

location / {
    try_files $uri $uri/ @router;
    index index.html index.php;
    error_page 403 = @router;
    error_page 404 = @router;
}

location @router {
    rewrite ^(.*)$ /router.php?$1;
}
like image 142
adrenalin Avatar answered Sep 27 '22 19:09

adrenalin


Well if it's always /data I would create a specific location for it, like this

location ~ /data/(.+).png {
    try_files $uri /serveImage.php?guid=$1;
}

Try this and tell me if it works.

like image 36
Mohammad AbuShady Avatar answered Sep 27 '22 17:09

Mohammad AbuShady