Reputation: 539
I'm serving static html using and would like to force trailing slashes. Redirecting when there's no slash is fine, but serving the actual html file is tricky. This regular expression isn't wokring
location ~* ^(.*)[^/]/$ {
try_files $1.html $1 $1/index.html $1/ =404;
}
So that should make /work/ load /work.html, /work or /work/index.html but it's just 404'ing.
I've got a few other redirects, but here's a synopsis:
/people.html should redirect to /people/ but server the file /people.html
Here's my full server block:
server {
listen 80;
root /vagrant/www;
index index.html index.htm;
server_name localhost;
rewrite ^(.*[^/])$ $1/ permanent;
if ($request_method !~ ^(GET|HEAD)$ ) {
return 444;
}
location = / {
try_files /index.html =404;
}
location = /index {
return 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;
}
Upvotes: 1
Views: 1988
Reputation: 4763
Why do you wish so hard to add a trailing slash when a location does not need it? Slash/No slash helps differentiating files from directories on the filesystem. It would save you from using try_files
, manually searching for $1
or $1/
...
location ~* ^(.+?)/$ {
try_files $1.html $1 $1/index.html $1/ =404;
}
should do the trick.
Note I used a non-greedy *
quantifier to avoid the capture eating the trailing slash.
I avoided to use (.*?)
for cleanliness sake, although it would have worked the same, since though theoretically matching the /
location special case, you have a location = /
which will match it and stop the search (thanks to the =
modifier).
Be careful with stacks of regex locations: order matters, which makes maintenance hard... Try to enclose those in prefix locations as much as possible.
Upvotes: 1