简体   繁体   中英

Nginx rewrite part of URL with GeoIP variables

I have a URL like this: https://example.com/home/anything/whatever

I need to rewrite this URL and replace the /home/ part with the variables from GeoIP and http-request-language: https://example.com/ch/de/anything/whatever

I have a location match on the root that already does this and this works:

location = / {
    rewrite ^ $location_uri$lang permanent;
}

Now i need this for the case above and i used:

location ~ /home/(.*) {
    rewrite ^/home/(.*)$ /$location_uri$lang/$1/ permanent;
}

The original reqeust part of the URL ($1) is not added to the end of the URL: https://example.com/ch/de//

If I remove the 2 variables $location_uri and $lang and replace them with a fix text (/ch/de) it works.

Is it possible to have these variables in the rewrite?

I managed to do it with 2 rewrites:

location ~ ^/home(.*)$ {
    rewrite ^/home(.*)$ /$location_uri$lang$request_uri permanent;
}

location ~ ^/ch/de/home(.*)$ {
    rewrite ^(.*)/home(.*)$ $1$2 permanent;
}

First I rewrite /home/ with the GeoIP vars and add the whole request URI including /home/. Then I make another location-match on the target-URI and remove the /home part.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM