Saturday 15 May 2010

nginx regex for static html files with trailing slashes -



nginx regex for static html files with trailing slashes -

i'm serving static html using , forcefulness trailing slashes. redirecting when there's no slash fine, serving actual html file tricky. regular look isn't wokring

location ~* ^(.*)[^/]/$ { try_files $1.html $1 $1/index.html $1/ =404; }

so should create /work/ load /work.html, /work or /work/index.html it's 404'ing.

i've got few other redirects, here's synopsis:

/people.html should redirect /people/ server file /people.html

here's total server block:

server { hear 80; root /vagrant/www; index index.html index.htm; server_name localhost; rewrite ^(.*[^/])$ $1/ permanent; if ($request_method !~ ^(get|head)$ ) { homecoming 444; } location = / { try_files /index.html =404; } location = /index { homecoming 301 $scheme://$host; } location ~* \.html$ { rewrite ^(.+)\.html$ $scheme://$host$1 permanent; } location ~* ^(.*)[^/]/$ { try_files $1.html $1 $1/index.html $1/ =404; } location / { try_files $uri.html $uri $uri/index.html $uri/ =404; } error_page 404 /404.html; error_page 500 502 503 504 /50x.html; include h5bp/basic.conf; }

why wish hard add together trailing slash when location not need it? slash/no slash helps differentiating files directories on filesystem. save using try_files, manually searching $1 or $1/...

location ~* ^(.+?)/$ { try_files $1.html $1 $1/index.html $1/ =404; }

should trick.

note used non-greedy * quantifier avoid capture eating trailing slash.

i avoided utilize (.*?) cleanliness sake, although have worked same, since though theoretically matching / location special case, have location = / match , stop search (thanks = modifier).

be careful stacks of regex locations: order matters, makes maintenance hard... seek enclose in prefix locations much possible.

regex nginx

No comments:

Post a Comment