H
H
Hecktosaurus2021-11-02 10:33:16
Apache HTTP Server
Hecktosaurus, 2021-11-02 10:33:16

How to use custom variables in RewriteCond?

I want to give avif-versions of pictures by means of a web server. They will be located in a subfolder at the root, and with the original path preserved. I want to set up a subfolder through a variable, so that later I don’t get lost when the script becomes more complicated.

The problem is that this variable is not processed in RewriteCond, it just returns a void. Can it be done?

.htaccess rules

RewriteEngine On
# префикс пути для avif-версий: /1.jpg -> /avif/1.jpg.avif
RewriteRule .* - [ENV=AVIF_CUSTOM_PATH:/avif]
# дебаг - заголовок отдастся, путь будет показан
Header set x-avif-custom-path %{AVIF_CUSTOM_PATH}e
# проверяю наличие и отдаю, если есть
# на этих шагах проблема, %{AVIF_CUSTOM_PATH} обрабатывается пустой, а если прописать "e" в конец,
# как сделано выше в Header set, то только она и добавится -> e/1.jpg
RewriteCond %{DOCUMENT_ROOT}%{AVIF_CUSTOM_PATH}%{REQUEST_URI}.avif -f
RewriteRule ^\/?(.*)\.(jpe?g|png)$ %{AVIF_CUSTOM_PATH}/$1.$2.avif [NC,T=image/avif,L]


Apache log
strip per-dir prefix: D:/OpenServer_540/domains/amo.test/1.jpg -> 1.jpg, referer: http://amo.test/1.jpg
applying pattern '.*' to uri '1.jpg', referer: http://amo.test/1.jpg
setting env variable 'AVIF_CUSTOM_PATH' to '/avif', referer: http://amo.test/1.jpg
strip per-dir prefix: D:/OpenServer_540/domains/amo.test/1.jpg -> 1.jpg, referer: http://amo.test/1.jpg
applying pattern '^\\/?(.*)\\.(jpe?g|png)$' to uri '1.jpg', referer: http://amo.test/1.jpg
RewriteCond: input='D:/OpenServer_540/domains/amo.test/1.jpg.avif' pattern='-f' => not-matched, referer: http://amo.test/1.jpg
pass through D:/OpenServer_540/domains/amo.test/1.jpg, referer: http://amo.test/1.jpg

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dodo512, 2021-11-02
@Hecktosaurus

%{ENV:AVIF_CUSTOM_PATH}
httpd.apache.org/docs/2.4/mod/mod_rewrite.html#rew...

%{ENV:variable}, where variable can be any environment variable, is also available. This is looked-up via internal Apache httpd structures and (if not found there) via getenv() from the Apache httpd server process.

RewriteEngine On
# префикс пути для avif-версий: /1.jpg -> /avif/1.jpg.avif
RewriteRule .* - [ENV=AVIF_CUSTOM_PATH:/avif]
# дебаг - заголовок отдастся, путь будет показан
Header set x-avif-custom-path %{AVIF_CUSTOM_PATH}e
# проверяю наличие и отдаю, если есть
RewriteCond %{DOCUMENT_ROOT}%{ENV:AVIF_CUSTOM_PATH}/$0.avif -f
RewriteRule ^.*\.(?:jpe?g|png)$ %{ENV:AVIF_CUSTOM_PATH}/$0.avif [NC,T=image/avif,L]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question