Home > Enterprise >  Nginx rewrite any arg name
Nginx rewrite any arg name

Time:04-23

I am trying to build a rewrite for CDN system which uses arguments to point to the data. All data is stored in the same location so any rewrite needs to wildcard rewrite the $arg_name and then pass the value for the data along. Turning this:

http://cdn.example.com/data/?main_loc=datastring

into this:

http://example.com/datastore/datastring

Using a location directive I can fetch the request to /data/, but from there I don't know what the rewrite would need to look like to do a "match any arg name" like main_loc, backup_loc etc. to pass its value as rewrite. Can I apply regex to match any $arg_name and use the value from that?

location ^~ /data/ {
    rewrite ^$arg_(\w*\_\w*)$ http://example.com/datastore/$1;
}

Or what would that look like?

CodePudding user response:

You could capture the arg value with the following map:

map $args $arg_value {
    ~=(.*) $1;
}

Then redirect to it:

location = /data/ {
    return 301 http://example.com/datastore/$arg_value;
}
  • Related