首页 > 解决方案 > Nginx rewrite rule is not working if hash in the url

问题描述

I have written nginx rewrite rule to redirect all request for /path/category except subcategory1. I am using below regular expression for match and it is working fine in regex tester. However, when I am providing same regex in Nginx conf then it is not working for negative lookahead if url contains the # character. Do you have any suggestions?

enter image description here

Regex tried so far:

^\/path\/category(?!.*(\bsubcategory1\b)).*$
^\/path\/category(([\/#]*)(?!.*(subcategory1))).*$

Rewrite Rule:

rewrite ^\/path\/category(?!.*(\bsubcategory1\b)).*$ https://new.host.com permanent;

Path Details: It should redirect to https://new.host.com which is working fine

/path/category
/path/category/
/path/category#/
/path/category/#/

skip the redirection for subcategory1 . It is not working for last 3 urls that contains hash.

/path/category/subcategory1
/path/category/subcategory1/
/path/category/subcategory1/dsadasd
/path/category#/subcategory1
/path/category/#/subcategory1
/path/category#/subcategory1/dadsd

标签: regexnginxurl-rewritingregex-lookaroundsnginx-location

解决方案


# 之后的 URI 中的任何内容都将被忽略,因为它应该是客户端,因此它永远不会到达 HTTP 服务器(例如 Nginx)。

如果正在处理的字符串中有#,Nginx 正则表达式将显示异常行为。

# 之后的部分称为片段

片段可以在客户端处理。

您可以使用 window.location.hash 来访问和处理片段。

这个 Javascript 示例在对process.html的请求中的参数中转换片段:

let param = window.location.hash;
param = param.substring(1); // remove #
param = '?' + param;
console.log('param=',param);
location.href = '/process.html' + param;

推荐阅读