gpt4 book ai didi

html - NGINX删除.html扩展名

转载 作者:技术小花猫 更新时间:2023-10-29 12:57:07 29 4
gpt4 key购买 nike

因此,我找到了删除页面上的.html扩展名的答案,此代码可以正常工作:

server {
listen 80;
server_name _;
root /var/www/html/;
index index.html;

if (!-f "${request_filename}index.html") {
rewrite ^/(.*)/$ /$1 permanent;
}

if ($request_uri ~* "/index.html") {
rewrite (?i)^(.*)index\.html$ $1 permanent;
}

if ($request_uri ~* ".html") {
rewrite (?i)^(.*)/(.*)\.html $1/$2 permanent;
}

location / {
try_files $uri.html $uri $uri/ /index.html;
}
}

但是,如果我打开mypage.com,它会将我重定向到mypage.com/index

通过将index.html声明为index可以解决此问题吗?任何帮助表示赞赏。

最佳答案

在NGINX中删除“.html”的“ chalice ”解决方案:
更新后的答案:这个问题激起了我的好奇心,然后我又进行了更深入的搜索,以寻找NGINX中.html重定向的“ chalice ”解决方案。这是我找到的答案的链接,因为我自己没有提出答案:https://stackoverflow.com/a/32966347/4175718
但是,我将举一个示例并说明其工作原理。这是代码:

location / {
if ($request_uri ~ ^/(.*)\.html) {
return 302 /$1;
}
try_files $uri $uri.html $uri/ =404;
}
这里发生的是对 if指令的巧妙使用。 NGINX在传入请求的 $request_uri部分上运行一个正则表达式。正则表达式检查URI是否具有.html扩展名,然后将URI的无扩展名部分存储在内置变量 $1中。
docs开始,因为花了我一段时间才弄清楚 $1的来源:

Regular expressions can contain captures that are made available for later reuse in the $1..$9 variables.


regex会检查是否存在不需要的.html请求,并有效地清理URI,使其不包含扩展名。然后,使用简单的 return语句,将请求重定向到现在存储在 $1中的经过清理的URI。
正如原始作者 cnst所解释的,与此相关的最好的部分是

Due to the fact that $request_uri is always constant per request, and is not affected by other rewrites, it won't, in fact, form any infinite loops.


与对任何 .html请求(包括不可见的内部重定向到 /index.html)的 操作的重写不同,此解决方案仅对用户可见的外部URI操作。
“try_files”做什么?
您仍然需要try_files指令,否则NGINX将不知道如何处理新清理的无扩展名URI。上面显示的try_files指令将首先尝试单独使用新的URL,然后使用扩展名“.html”尝试它,然后将其作为目录名称尝试。
NGINX文档还解释了默认try_files指令如何工作。默认的try_files指令的顺序与上面的示例不同,因此下面的说明并不完美:

NGINX will first append .html to the end of the URI and try to serve it. If it finds an appropriate .html file, it will return that file and will maintain the extension-less URI. If it cannot find an appropriate .html file, it will try the URI without any extension, then the URI as a directory, and then finally return a 404 error.


更新:正则表达式做什么?
上面的答案涉及到正则表达式的使用,但是对于那些仍然好奇的人,这是更具体的解释。使用以下正则表达式(regex):
^/(.*)\.html
分解为:^:指示行的开头。/:从字面上匹配字符“/”。 NGINX中的正斜杠不需要转义。(.*):捕获组:无限匹配任何字符\.:匹配字符“。”从字面上看。必须使用反斜杠将其转义。html:从字面上匹配字符串“html”。
捕获组(.*)是包含URL的非“.html”部分的内容。以后可以用$1变量引用它。然后将NGINX配置为重试该请求(return 302 /$1;),并且try_files指令在内部重新添加“.html”扩展名,以便可以找到该文件。
更新:保留查询字符串
要保留传递给.html页的查询字符串和参数,可以将return语句更改为:
return 302 /$1$is_args$args;
这应该允许诸如/index.html?test之类的请求重定向到/index?test而不是/index

注意,这被认为是`if`指令的安全用法。
在NGINX页面上,如果是邪恶的:

The only 100% safe things which may be done inside if in a location context are:

return ...;

rewrite ... last;



另外,请注意,您可以将“302”重定向换成“301”。301重定向是永久性的,并由Web浏览器和搜索引擎缓存。如果您的目标是从搜索引擎已编制索引的页面中永久删除.html扩展名,则将需要使用301重定向。但是,如果要在实时站点上进行测试,则最佳做法是从302开始,仅在完全确信配置正确工作时才移至301

关于html - NGINX删除.html扩展名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38228393/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com