O
O
Oleg2018-04-03 16:18:09
Nginx
Oleg, 2018-04-03 16:18:09

How to elegantly write many redirects by ID using map in NGINX?

Something I completely got confused with map with these map and if.
There is an array with more than 1000 IDs
100
121
34948
34
465
7741
You need to make a redirect like this
rewrite ^/cat/article/ ID $ https://site.com/cat/article/post ID / permanent;
There are IDs that need to be redirected, let's say 5,4,55,21... is needed, but 1,2,3,4,6... is no longer there. The array contains exactly those IDs that need to be redirected.
I read the documentation, looked at the examples. While thinking about this option

map $uri $new_uri {
…
/cat/article/100$ https://site.com/cat/article/post100/
/cat/article/121$ https://site.com/cat/article/post121/
/cat/article/34948$ https://site.com/cat/article/post34948/
…
}

server {
…
if ($new_uri) {
rewrite ^ $new_uri permanent;
. . .
}

but it seems to me that it is cumbersome. you need to write the whole URL. How to implement a configuration so that only IDs are written in the map?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lynn "Coffee Man", 2018-04-03
@Lynn

I would do like this:

map $uri $should_redirect {
  /cat/article/4 1;
  /cat/article/5 1;
  /cat/article/21 1;
  /cat/article/55 1;
  ...
}

location /cat/article/ {
  if ($should_redirect) {
    rewrite ^/cat/article/([0-9]+)$ https://site.com/cat/article/post$1/ permanent;
  }
  ...
}

Perhaps the enumeration inside the map needs to be moved to a separate file and use include . See nginx.org/ru/docs/http/ngx_http_map_module.html#map.
It may also be necessary to pick up new values ​​for map_hash_bucket_size / map_hash_max_size . See nginx.org/ru/docs/hash.html
It was
------------
I don't understand why map is here?
Why is simple rewrite bad?
location /cat/article/ {
    rewrite ^/cat/article/([0-9]+)$ https://site.com/cat/article/post$1/;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question