Roopendra
Roopendra

Reputation: 7776

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

Upvotes: 0

Views: 1040

Answers (1)

Edu_Godoy
Edu_Godoy

Reputation: 81

Anything in the URI after # is ignored because it is supposed to be client side so it never gets to HTTP server (Nginx for instance).

Nginx regex will show abnormal behavior if a # is in the string under processing.

The part after # is called fragment.

The fragment can be processed at client side.

You can use window.location.hash to access and process fragments.

This Javascript example transform fragment in parameters in a request to process.html :

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

Upvotes: 2

Related Questions