How to hide file extension in nginx
Coming from an Apache background, in the past I have hidden .html file extensions using a pair of rewrite rules:
RewriteCond %{THE_REQ开发者_Python百科UEST} ^(GET|HEAD)\ /.+\.html\ HTTP
RewriteRule ^(.+)\.html$ http://%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^.+$ %{REQUEST_FILENAME}.html [L]
nginx's rewriting capabilities are different, a possible solution lies here however, the nginx wiki suggests that if at all possible avoiding ifs is the best solution, and discusses using (try_files
) instead. I was wondering whether anyone had the best way to implement something like this, as whilst:
try_files $uri $uri.html =404;
works in some cases, you would get massive redirect problems etc. Is there any way to avoid ifs in this case?
You would use the try_files directive like so:
location / {
try_files $uri $uri.html =404;
}
this does the following for each uri that matches the location block
- check if there's an exact match file, if so serve it
- if no exact match was found, then try adding .html to the request
- if that wasn't found either return a 404
there's no redirecting at all in that, just nginx checking several options in turn.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^.+$ %{REQUEST_FILENAME}.html [L]
the first 2 lines of that are basically 1. and 2. except that nginx doesn't need to rewrite the url as the try_files directive makes it smart enough to just return the request when the match is found
精彩评论