Использование переменных окружения в RewriteRule match - проще в обслуживании и меньше - PullRequest
3 голосов
/ 20 марта 2019

У меня есть куча переписываний для очень старого сайта, который имел много разных структур каталогов. Требуется около 140 перенаправлений, и вот пример структуры:

# First file set to first destination
RewriteRule ^(dir-one|dir-two|dir-three)\/(file-one|file-two|file-three)\/?$ /destination-one [R=301,L]

# Second file set to second destination
RewriteRule ^(dir-one|dir-two|dir-three)\/(file-four|file-five|file-six)\/?$ /destination-two [R=301,L]

# Third file set to third destination
RewriteRule ^(dir-one|dir-two|dir-three)\/(file-seven|file-eight|file-nine)\/?$ /destination-three [R=301,L]

# etc etc... Same sort of thing another 137 times!

Как вы можете видеть, здесь много повторяющейся информации в начальном совпадении каталога (dir-one|dir-two|dir-three).

Я хотел бы - по возможности сделать список каталогов легко обновляемым и задаться вопросом, будут ли работать переменные среды. Вот что я попробовал:

# setting the dir names in the ENV:
RewriteRule .* - [E=DIRS:"dir-one|dir-two|dir-three"]

# First file set to first destination
RewriteRule ^(%{ENV:DIRS})\/(file-one|file-two|file-three)\/?$ /destination-one [R=301,L]

# Second file set to second destination
RewriteRule ^(%{ENV:DIRS})\/(file-four|file-five|file-six)\/?$ /destination-two [R=301,L]

# Third file set to third destination
RewriteRule ^(%{ENV:DIRS})\/(file-seven|file-eight|file-nine)\/?$ /destination-three [R=301,L]

Это не работает. Я знаю, что ENV устанавливается (см. Скриншот ниже), но они не используются в RewriteRules. Что я делаю не так, это вообще возможно, есть ли лучший способ?

Если это сработает, я бы, вероятно, расширил его, чтобы наборы файлов сохранялись в формате ENV, поэтому наборы файлов также можно обновлять в одном месте.

Спасибо!

Screeny showing Env Vars in phpinfo

Некоторые уточнения ...

Мой пример не показал, чего я пытаюсь добиться очень хорошо. Вот более реальный пример:

# What I have now. Note the repeated 'sections|categories|areas' part:

RewriteRule ^(sections|categories|areas)\/(car|plane|train)\/?$ /transport [R=301,L]
RewriteRule ^(sections|categories|areas)\/(pig|cow|goat|kangaroo)\/?$ /animals [R=301,L]
RewriteRule ^(sections|categories|areas)\/(cheese|fish|turnips)\/?$ /food [R=301,L]
# etc etc... Same sort of thing another 137 times!
# What I'm hoping is possible. It will allow me to add or edit the
# first match (sections|categories|areas) in one place and not 140 places. 

RewriteRule .* - [E=DIRS:"sections|categories|areas"]

RewriteRule ^(%{ENV:DIRS})\/(car|plane|train)\/?$ /transport [R=301,L]
RewriteRule ^(%{ENV:DIRS})\/(pig|cow|goat|kangaroo)\/?$ /animals [R=301,L]
RewriteRule ^(%{ENV:DIRS})\/(cheese|fish|turnips)\/?$ /food [R=301,L]

Таким образом, первое совпадение всегда одинаково для каждого перезаписи. Различное сопоставление между вторым совпадением и местом назначения. то есть все машины едут на /transport, все животные едут на /animals и т. д. и т. д.

Моя главная цель - не повторять первый матч 140 раз. Если моя цель глупа, пожалуйста, так и скажите :)

Спасибо!

1 Ответ

2 голосов
/ 20 марта 2019

Матч против ENV в RewriteCond, а не в RewriteRule, например:

RewriteRule ^(dir-one|dir-two|dir-three)/(.*)$ - [E=DIRS:$1]

RewriteCond %{ENV:DIRS} ^dir-one
RewriteRule ^([^\/]+)\/(file-one|file-two|file-three)\/?$ /destination-one [R=301,L]

RewriteCond %{ENV:DIRS} ^dir-two
RewriteRule ^([^\/]+)\/(file-four|file-five|file-six)\/?$ /destination-two [R=301,L]

RewriteCond %{ENV:DIRS} ^dir-three
RewriteRule ^([^\/]+)\/(file-seven|file-eight|file-nine)\/?$ /destination-three [R=301,L]

Более того, если вы хотите перенаправить их только в новое место, и нет никакой связи между старым и новым uri, как я вижу, сделайте их такими:

RewriteRule ^(dir-one|dir-two|dir-three)/(.*)/?$ - [E=DIRS:$1-$2]

RewriteCond %{ENV:DIRS} ^dir-one\-(file-one|file-two|file-three)
RewriteRule ^  /destination-one [R=301,L]

RewriteCond %{ENV:DIRS} ^dir-two\-(file-four|file-five|file-six)
RewriteRule ^  /destination-two [R=301,L]

RewriteCond %{ENV:DIRS} ^dir-three\-(file-seven|file-eight|file-nine)
RewriteRule ^    /destination-three [R=301,L]

Обновление:

Согласно вашему обновлению попробуйте это:

RewriteEngine on

RewriteRule ^(sections|categories|areas)/(.*)/?$   -   [E=DIRS:$1-$2]

RewriteCond %{ENV:DIRS} ^(.+)\-(car|plane|train)
RewriteRule ^  /transport  [R=301,L]

RewriteCond %{ENV:DIRS} ^(.+)\-(pig|cow|goat|kangaroo)
RewriteRule ^  /animals  [R=301,L]

RewriteCond %{ENV:DIRS} ^(.+)\-(cheese|fish|turnips)
RewriteRule ^  /food  [R=301,L]

Примечание: очистить кеш браузера и протестировать

...