ALT Linux Sisyphus discussions
 help / color / mirror / Atom feed
From: Sergey Vlasov <vsu@altlinux.ru>
To: sisyphus@lists.altlinux.org
Subject: Re: [sisyphus] replace regexp в nginx rewrite правиле
Date: Sat, 26 Nov 2011 21:17:33 +0400
Message-ID: <20111126171733.GA6371@atlas.home> (raw)
In-Reply-To: <CAN5SjABwU8AE4R=8b155ViHbr_2vZ98tjpQN0b+R_BE9tA2HMw@mail.gmail.com>

[-- 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 --]

  reply	other threads:[~2011-11-26 17:17 UTC|newest]

Thread overview: 3+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2011-11-26 11:14 Michael Bykov
2011-11-26 17:17 ` Sergey Vlasov [this message]
2011-11-27  5:07   ` Michael Bykov

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20111126171733.GA6371@atlas.home \
    --to=vsu@altlinux.ru \
    --cc=sisyphus@lists.altlinux.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link

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