Tuesday, June 30, 2009

Nginx rewrite for user subdomains

For example you need to store few userpics for each user with possibility to set default userpic. First we must determine that for static content we will use nginx as one of the fastest web server. Userpics will be stored by scheme: "files/userpics/[first two letters from username]/[username]/"
directories scheme:

root@server:~# tree files
files
`-- userpics
|-- te
| |-- test11
| | |-- 0.gif
| | |-- 1246347162.gif
| | |-- 1246362446.jpg
| | `-- 1246363739.gif
| `-- test44
| |-- 0.gif
| |-- 1246365659.gif
| `-- 1246366597.gif
`-- tu
|-- turkish
| |-- 0.gif
| |-- 1246357650.gif
| |-- 1246357669.gif
| `-- 1246363992.gif
`-- tuzik
|-- 0.jpg
|-- 1246365938.jpg
`-- 1246365974.jpg


Default userpic will be addressed to 0.[jpg|png|gif] (file extension depends on extension the parent file)
Http request http://test11.mydomain.com/userpics/1246347162.gif must return this file:
/opt/www/files/userpics/te/test11/1246347162.gif
if file does not exist, nginx must return default userpic for this user:
/opt/www/files/userpics/te/test11/0.[jpg|png|gif]
if default userpic does not exist, nginx return default userpic for all users "/userpic-default.png"

part of nginx.conf:

location /userpics/ {
default_type image/jpeg;
root /opt/www;
access_log /var/log/nginx/static.access.log main;
if ($host ~* "(..)(.*)\.mydomain\.com") {
set $a $1;
set $b $2;
rewrite ^/userpics/(.*)$ /files/userpics/$a/$a$b/$1;
}
if (!-f $request_filename) {
rewrite ^/files/userpics/(.*)$ /files/userpics/$a/$a$b/0.jpg;
}
if (!-f $request_filename) {
rewrite ^/files/userpics/(.*)$ /files/userpics/$a/$a$b/0.gif;
}
if (!-f $request_filename) {
rewrite ^/files/userpics/(.*)$ /files/userpics/$a/$a$b/0.png;
}

break;
error_page 404 =200 /userpic-default.png;

}

UPD Best way: don't use "if" in location level.
try_files /files/userpics/$a/$a$b/0.jpg /files/userpics/$a/$a$b/0.gif /files/userpics/$a/$a$b/0.png /userpic-default.png;

No comments:

Post a Comment