* [sisyphus] replace regexp в nginx rewrite правиле @ 2011-11-26 11:14 Michael Bykov 2011-11-26 17:17 ` Sergey Vlasov 0 siblings, 1 reply; 3+ messages in thread From: Michael Bykov @ 2011-11-26 11:14 UTC (permalink / raw) To: ALT Linux Sisyphus discussions Салют, господа, помогите, пожалуйста, кто чем может, сами мы не местные... мне нужно в правиле nginx заменить путь с /a/b/c/d... etc на /a_b_c_d... etc поиск в гугле не дал результатов ввиду идиотизма проблемы. Но в данном случае очень нужно. В сизифовском nginx нет perl'а, на перле было бы проще Вот это неправильно: rewrite / _ permanent; rewrite ^(([^/]*)/) $2/ permanent; а как правильно? Сорри :( -- М. http://diglossa.ru xmpp://m.bykov@jabber.ru ^ permalink raw reply [flat|nested] 3+ messages in thread
* Re: [sisyphus] replace regexp в nginx rewrite правиле 2011-11-26 11:14 [sisyphus] replace regexp в nginx rewrite правиле Michael Bykov @ 2011-11-26 17:17 ` Sergey Vlasov 2011-11-27 5:07 ` Michael Bykov 0 siblings, 1 reply; 3+ messages in thread From: Sergey Vlasov @ 2011-11-26 17:17 UTC (permalink / raw) To: sisyphus [-- Attachment #1: Type: text/plain, Size: 1814 bytes --] On Sat, Nov 26, 2011 at 02:14:01PM +0300, Michael Bykov wrote: > господа, помогите, пожалуйста, кто чем может, сами мы не местные... > > мне нужно в правиле nginx заменить путь с /a/b/c/d... etc на /a_b_c_d... etc > > поиск в гугле не дал результатов ввиду идиотизма проблемы. Но в данном > случае очень нужно. > > В сизифовском nginx нет perl'а, на перле было бы проще > > Вот это неправильно: > > rewrite / _ permanent; Действительно, это работать не будет, поскольку rewrite в nginx всегда заменяет весь URI, а не меняет в существующем только подстроку, соответствующую регулярному выражению. > rewrite ^(([^/]*)/) $2/ permanent; > > а как правильно? Можно попробовать сгородить что-то такое: location ~ "^/([^/]*/){11}" { return 404; } location ~ ^/[^/]*/ { rewrite ^(/[^/]*)/([^/]*)$ $1_$2 permanent; rewrite ^(/[^/]*)/(.*)$ $1_$2 last; } location / { # тут обрабатываем запрос, в котором не было "/" } Первый location более красиво обрабатывает запросы, которые содержат более 10 лишних "/" (чтобы на них не выдавалась ошибка 500). Второй location обрабатывает "нормальные" запросы с лишними "/". Первый rewrite срабатывает, когда в запросе остался последний лишний "/" - в этом случае нужно отдать redirect. Второй rewrite обрабатывает случаи, когда "/" несколько - в этом случае заменяется первое вхождение, после чего обработка URI начинается заново (допускается до 10 таких циклов; если этого мало, можно добавить перед ним ещё rewrite, заменяющий сразу несколько вхождений, и соответствующим образом изменить ограничение в первом location). Если количество "/" жёстко ограничено, можно просто прописать правила для всех нужных вариантов, чтобы не возиться с рекурсией через last. [-- Attachment #2: Digital signature --] [-- Type: application/pgp-signature, Size: 198 bytes --] ^ permalink raw reply [flat|nested] 3+ messages in thread
* Re: [sisyphus] replace regexp в nginx rewrite правиле 2011-11-26 17:17 ` Sergey Vlasov @ 2011-11-27 5:07 ` Michael Bykov 0 siblings, 0 replies; 3+ messages in thread From: Michael Bykov @ 2011-11-27 5:07 UTC (permalink / raw) To: ALT Linux Sisyphus discussions 26 ноября 2011 г. 21:17 пользователь Sergey Vlasov <vsu@altlinux.ru> написал: > On Sat, Nov 26, 2011 at 02:14:01PM +0300, Michael Bykov wrote: >> господа, помогите, пожалуйста, кто чем может, сами мы не местные... >> >> мне нужно в правиле nginx заменить путь с /a/b/c/d... etc на /a_b_c_d... etc >> >> поиск в гугле не дал результатов ввиду идиотизма проблемы. Но в данном >> случае очень нужно. >> >> В сизифовском nginx нет perl'а, на перле было бы проще >> >> Вот это неправильно: >> >> rewrite / _ permanent; > > Действительно, это работать не будет, поскольку rewrite в nginx всегда > заменяет весь URI, а не меняет в существующем только подстроку, > соответствующую регулярному выражению. > >> rewrite ^(([^/]*)/) $2/ permanent; >> >> а как правильно? > > Можно попробовать сгородить что-то такое: > > location ~ "^/([^/]*/){11}" { > return 404; > } > > location ~ ^/[^/]*/ { > rewrite ^(/[^/]*)/([^/]*)$ $1_$2 permanent; > rewrite ^(/[^/]*)/(.*)$ $1_$2 last; > } > > location / { > # тут обрабатываем запрос, в котором не было "/" > } > > Первый location более красиво обрабатывает запросы, которые содержат > более 10 лишних "/" (чтобы на них не выдавалась ошибка 500). > > Второй location обрабатывает "нормальные" запросы с лишними "/". > Первый rewrite срабатывает, когда в запросе остался последний лишний > "/" - в этом случае нужно отдать redirect. Второй rewrite > обрабатывает случаи, когда "/" несколько - в этом случае заменяется > первое вхождение, после чего обработка URI начинается заново > (допускается до 10 таких циклов; если этого мало, можно добавить перед > ним ещё rewrite, заменяющий сразу несколько вхождений, и > соответствующим образом изменить ограничение в первом location). > > Если количество "/" жёстко ограничено, можно просто прописать правила > для всех нужных вариантов, чтобы не возиться с рекурсией через last. > > _______________________________________________ > Sisyphus mailing list > Sisyphus@lists.altlinux.org > https://lists.altlinux.org/mailman/listinfo/sisyphus > Сергей, спасибо за замечательный ответ! -- М. http://diglossa.ru xmpp://m.bykov@jabber.ru ^ permalink raw reply [flat|nested] 3+ messages in thread
end of thread, other threads:[~2011-11-27 5:07 UTC | newest] Thread overview: 3+ messages (download: mbox.gz / follow: Atom feed) -- links below jump to the message on this page -- 2011-11-26 11:14 [sisyphus] replace regexp в nginx rewrite правиле Michael Bykov 2011-11-26 17:17 ` Sergey Vlasov 2011-11-27 5:07 ` Michael Bykov
ALT Linux Sisyphus discussions This inbox may be cloned and mirrored by anyone: git clone --mirror http://lore.altlinux.org/sisyphus/0 sisyphus/git/0.git # If you have public-inbox 1.1+ installed, you may # initialize and index your mirror using the following commands: public-inbox-init -V2 sisyphus sisyphus/ http://lore.altlinux.org/sisyphus \ sisyphus@altlinux.ru sisyphus@altlinux.org sisyphus@lists.altlinux.org sisyphus@lists.altlinux.ru sisyphus@lists.altlinux.com sisyphus@linuxteam.iplabs.ru sisyphus@list.linux-os.ru public-inbox-index sisyphus Example config snippet for mirrors. Newsgroup available over NNTP: nntp://lore.altlinux.org/org.altlinux.lists.sisyphus AGPL code for this site: git clone https://public-inbox.org/public-inbox.git