Nginx try_files

Nginx try_files

如下所示,当我们有多个HTML文件对应多个URL,想最快把URL中的后缀 .html 去除掉,又不影响其他接口。该怎样做呢?

# 未去掉前
https://test.com/about.html
https://test.com/home.html
https://test.com/fdsagas

# 去掉.html后
https://test.com/about
https://test.com/home


这个时候普通的rewrite做起来就很繁琐,try_files就登场了。Nginx配置如下

location / {
    # 指定nginx查找这个路径下文件 
    root /root/test/ui;
    # 重定向所有.html后缀
    # 重定向前 /about.html -> 重定向后 /about
    if ($request_uri ~ ^/(.*)\.html$) {
    	return 301 /$1;
    }
    # Tries the uri, .html file and the news prefix.
    # 1.$uri -> /about
    # 2.$uri/ -> /about/
    # 3.$uri.html -> /about.html
    # 4./index.html?$args
    # 从第一个开始匹配这个这些文件名 匹配不到就直接返回最有一个文件 /index.html
    try_files $uri $uri/ $uri.html /index.html?$args;
}

无解释配置

location / {
    root /root/test/ui;
    if ($request_uri ~ ^/(.*)\.html$) {
        return 301 /$1;
    }
    try_files $uri $uri/ $uri.html /index.html?$args;
}
posted @ 2021-09-13 15:29  TY520  阅读(24773)  评论(0编辑  收藏  举报