Nginx:请求不带扩展名的文件

Tui*_*lak 1 nginx

如何在没有扩展名的情况下在 nginx 服务器上请求 html 页面?

即:example.com/about 应该返回 example.com/about.html。对于所有 html 页面都应该如此。

我有一些类似的事情:

try_files $uri $uri.html;
index  index.html;
Run Code Online (Sandbox Code Playgroud)

这是有效的,但是访问 example.com/ 会导致 403 Forbidden:

2015/01/20 19:26:11 [error] 32618#0: *373061 access forbidden by rule
Run Code Online (Sandbox Code Playgroud)

访问不存在的页面 (example.com/bla) 会导致重定向循环:

2015/01/20 19:26:57 [error] 32620#0: *373065 rewrite or internal redirection cycle while internally redirecting to "/bla.html.html.html.html.html.html.html.html.html.html.html"
Run Code Online (Sandbox Code Playgroud)

更新了完整的 nginx 配置:

server {
    listen          [::]:80;
    server_name     example.com;

    access_log  /var/log/nginx/access.log;
    error_log   /var/log/nginx/error.log;
    root   /var/www/example/;
    try_files $uri $uri.html /index.html =404;
    index  index.html;
    expires max;
    autoindex off;

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
        deny  all;
    }
}
Run Code Online (Sandbox Code Playgroud)

Hyp*_*ppy 5

将 try_files 行修改为如下所示:

try_files $uri $uri.html /index.html =404;
Run Code Online (Sandbox Code Playgroud)

您看到循环的原因是,如果在搜索过程中找不到有效位置,try_files 将强制重定向到最后一个条目。

进一步阅读和参考:http://wiki.nginx.org/HttpCoreModule#try_files