nginx 匹配路径中的文件夹并且没有 .html 需要重写并附加 .html
nginx match a folder in path and with no .html which needs to rewrite with .html appended
我有一个 URL,它在路径中包含子文件夹,可能包含也可能不包含 .html.
如果 url 路径中包含“/p/”并且末尾没有 .html,我想匹配。
如果满足这些条件,我想附加 .html
我尝试过使用 if 语句和位置,但没有成功。
这是我试过但没有成功的方法:
if ($uri ~ ^(.*)/p/(.*)$){
rewrite ^(.+)/$ .html permanent;
}
if ($uri ~ ^(.*)/p/(.*[^.html])$){
rewrite ^(.+)/$ .html permanent;
}
location ~ ^(.*)/p/(.*[^.html])$ {
rewrite ^(.+)/$ .html permanent;
}
您需要正面展望 (?=.*\/p\/)
以确保存在 /p/
和负面展望 (?!.*\.html$)
以确保字符串不以 .html
结尾.正确的正则表达式是这样的,
^(?=.*\/p\/)(?!.*\.html$).+$
然后尝试按照您的方式重写您的 if 条件,应该是这样,
location ~ ^(?=.*\/p\/)(?!.*\.html$).+$ {
rewrite ^(.+)/$ .html permanent;
}
此外,在您的正则表达式 [^.html]
中,这是一个字符否定,只会否定 ^
之后字符集中存在的某些字符,并且要否定一系列字符,您需要使用否定像我在正则表达式中所做的那样向前看模式。
location ~ ^(?=.*\/p\/)(?!.*\.html$).+$ {
try_files $uri $uri/ @rewrite;
}
location @rewrite {
rewrite ^(.+)$ .html permanent;
}
我有一个 URL,它在路径中包含子文件夹,可能包含也可能不包含 .html.
如果 url 路径中包含“/p/”并且末尾没有 .html,我想匹配。 如果满足这些条件,我想附加 .html
我尝试过使用 if 语句和位置,但没有成功。
这是我试过但没有成功的方法:
if ($uri ~ ^(.*)/p/(.*)$){
rewrite ^(.+)/$ .html permanent;
}
if ($uri ~ ^(.*)/p/(.*[^.html])$){
rewrite ^(.+)/$ .html permanent;
}
location ~ ^(.*)/p/(.*[^.html])$ {
rewrite ^(.+)/$ .html permanent;
}
您需要正面展望 (?=.*\/p\/)
以确保存在 /p/
和负面展望 (?!.*\.html$)
以确保字符串不以 .html
结尾.正确的正则表达式是这样的,
^(?=.*\/p\/)(?!.*\.html$).+$
然后尝试按照您的方式重写您的 if 条件,应该是这样,
location ~ ^(?=.*\/p\/)(?!.*\.html$).+$ {
rewrite ^(.+)/$ .html permanent;
}
此外,在您的正则表达式 [^.html]
中,这是一个字符否定,只会否定 ^
之后字符集中存在的某些字符,并且要否定一系列字符,您需要使用否定像我在正则表达式中所做的那样向前看模式。
location ~ ^(?=.*\/p\/)(?!.*\.html$).+$ {
try_files $uri $uri/ @rewrite;
}
location @rewrite {
rewrite ^(.+)$ .html permanent;
}