Reputation: 13
I have a problem with redirect url to url in nginx:
for example I have a link:
https://example.com/oferty-specjalne/szczegoly-oferty?OfferID=124296
working function:
location ^/oferty-specjalne/szczegoly-oferty(.*)$ {
return 301 https://example.com/oferty-specjalne/; }
not working functions:
location ~ ^/oferty-specjalne/szczegoly-oferty\?OfferID=(124170|124296|124299|123483|63788|97002)$ {
return 301 https://example.com/oferty-specjalne/; }
location ~ ^/oferty-specjalne/szczegoly-oferty?OfferID=(.*)$ {
return 301 https://example.com/oferty-specjalne/$1; }
location ^/oferty-specjalne/szczegoly-oferty?OfferID=97002 {
return 301 https://example.com/oferty-specjalne/; }
I checked the regexes in the testers and everything is ok. I am asking for information where I am making a mistake and how I can solve it, or maybe for example.
Upvotes: 1
Views: 55
Reputation: 49672
The part of the URI following the ?
is the query string (or arguments) and is not part of the normalised URI used by the location
and rewrite
directives - so your rules will never match. See this document for details.
If you have complex regular expressions that need to match against the entire URI (including the query string) you need to use the $request_uri
variable. This can be tested using an if
or a map
. With more than a few regular expressions, a map
is the preferred solution.
For example:
map $request_uri $redirect {
default 0;
~^/oferty-specjalne/szczegoly-oferty\?OfferID=(124170|124296|124299|123483|63788|97002)$
/oferty-specjalne/;
~^/oferty-specjalne/szczegoly-oferty\?OfferID=(?<offerid>.*)$ /oferty-specjalne/$offerid;
~^/oferty-specjalne/szczegoly-oferty\?OfferID=97002 /oferty-specjalne/;
~^/oferty-specjalne/szczegoly-oferty /oferty-specjalne/;
}
server {
...
if ($redirect) {
return 301 $redirect;
}
Regular expressions are evaluated in order until a matching rule is found, so order the rules with most specific first and least specific last.
Use named captures, as the numeric captures can go out of scope.
You do not need to specify the scheme or domain name if they are the same.
The map
directive sits outside of the `server block.
See this document for details.
Upvotes: 0