R
R
rinokonli2015-01-08 11:57:01
Nginx
rinokonli, 2015-01-08 11:57:01

How to make nginx redirect with regular expressions?

Good day everyone! plz tell me how to do the following using nginx and regular expressions:
there are urls on the site - they are all in this format: the
first type of catch:
www.site.ru/catalog/cat/1-razdel-odin.html
need a redirect to this url:
www.site.ru/razdel-odin
(that is, we remove /cataloc/cat/, remove the numbers at the end and cut off ".html")
the second type of catch:
www.site.ru/catalog/1-razdel-odin/157- podokonniki.html
needs a redirect to the following url:
www.site.ru/razdel-odin/podokonniki
(that is, we remove /cataloc/, remove the numbers in the names of subfolders and at the end and cut off ".html")
the third type of catch
is www.site. ru/catalog/18-product-dlya-dachi/292-sadov... we
need a redirect to this URL:
www.site.ru/product-dlya-dachi/sadovaya-mebel/derev...
(that is, we remove /cataloc/, remove the numbers in the names in the subfolders, except for the very last part of the url, there you need to move the numbers to the end of the url-through dash, and cut ".html" at the end)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Zhavoronkov, 2015-01-08
@rinokonli

The addresses are very similar and it would be possible to get by with one expression with the /g modifier:
But since in nginx it is impossible to use /g when parsing the address, each case must be broken down separately:

if ($uri ~ "/catalog/cat/[0-9]+-([-\w]+)\.html") {
  rewrite /catalog/cat/[0-9]+-([-\w]+)\.html /$1 redirect;
}

if ($uri ~ "/catalog/[0-9]+-([-\w]+)/[0-9]+-([-\w]+)\.html") {
  rewrite /catalog/[0-9]+-([-\w]+)/[0-9]+-([-\w]+)\.html /$1/$2 redirect;
}

if ($uri ~ "/catalog/[0-9]+-([-\w]+)/[0-9]+-([-\w]+)/[0-9]+-([-\w]+)\.html") {
  rewrite /catalog/[0-9]+-([-\w]+)/[0-9]+-([-\w]+)/[0-9]+-([-\w]+)\.html /$1/$2/$3 redirect;
}

You can also try to do it through map.

R
rinokonli, 2015-01-08
@rinokonli

thank! works great
but ran into another incomprehensible problem, I'm trying to apply the given template to another situation where you need to leave /catalog/ but remove the numbers further in the url www.site.ru/catalog/1-razdel-odin/157-podokonniki.html
bring
www .site.ru/catalog/1-razdel-odin/157-podokonniki.html
for some reason the
template
doesn't work

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question