Welcome! Log In Create A New Profile

Advanced

nginx path finding

Posted by tsvetanov 
nginx path finding
February 06, 2010 12:28PM
Hello.

I'm using nginx over a year now for my image sharing website and i had no problems until now.
The problem began to appear when my website reached 300,000+ images, which i keep in one directory.
After searching through forums I finally found out a solution to my problem - dividing and storing the files in different subdirectories, defined by the filenames of the images. Example: file 123456.jpg goes to /images/12/34/123456.jpg etc.
So far so good. But this kind of change requires tweaking and adjusting the php code itself to serve the images from the correct directories, which is the last thing i wanna mess around with. I was wondering if there is a way that function could be made by using nginx.
For example: server receives file request "/images/123456.jpg". Ok, but the file isn't there - it's in the /images/12/34/ subdirectory, so nginx takes the first two chars of the filename, then the 3rd and the 4th one and then checks if that file exists in this folder. This way a php correction won't be needed and things should be much faster than the other way. Another advantage is that links to the website's images across the internet won't broke after the change is made using nginx. Am i right?

Please, could someone try to write a function / if statement for this to work?
I will be most pleased.

Thanks in advance and excuse my english.
Re: nginx path finding
February 06, 2010 01:01PM
Your English is quite fine.

You could try something like:

[code]
location /path/to/images/ {
try_files $uri $uri/ @fallback;
}

location @fallback {
rewrite "^/path/to/images/([\d]{2})([\d]{2})(.*)$" /path/to/images/$1/$2/$1$2$3 last;
}
[/code]


The "try_files" directive will look for the file in the uri requested, serve it if it's there, serve the index file of the directory if the requested uri has a trailing slash, and then go to @fallback which is an internal redirect. It (should) rewrite as you requested though my regex is not superb and it may need some tweaking. Of course this assumes that you are always using two 2-digit subdirectories if the file is not where it's "supposed" to be.

--
Jim Ohlstein
Re: nginx path finding
February 07, 2010 09:50AM
Works like a charm! Thank you very much, Jim!
Sorry, only registered users may post in this forum.

Click here to login

Online Users

Guests: 261
Record Number of Users: 8 on April 13, 2023
Record Number of Guests: 500 on July 15, 2024
Powered by nginx      Powered by FreeBSD      PHP Powered      Powered by MariaDB      ipv6 ready