大网数据广告活动
服务器运维问答

Apache RewriteRule on VirtualHosts doesn't work with group capture regex

· 52CE 我爱测

I need to create a RewriteRule to delegate an URL path like /tdg/image.jpg?mode=crop&width=300&height=300 to a local proxy. The proxy needs the given URL be transformed into the following format. http://localhost:8888/unsafe/300x…

问题原文

原帖链接 · Jonas Porto · CC BY-SA 3.0

I need to create a RewriteRule to delegate an URL path like /tdg/image.jpg?mode=crop&width=300&height=300 to a local proxy.

The proxy needs the given URL be transformed into the following format.

http://localhost:8888/unsafe/300x300/smart/tdg/image.jpg

I tried first using ProxyPassMatch apache directive but I can't retrieve the width and height data from the query string.

ProxyRequests On
ProxyPreserveHost On
ProxyPassMatch ^\/(tdg.+\.(?:png|jpeg|jpg|gif))\?mode=crop.+width=(d+)&height=(d+) http://localhost:8888/unsafe/$2x$3/smart/$1

I also tried RewriteRule

RewriteEngine On
RewriteRule ^\/(tdg.+\.(?:png|jpeg|jpg|gif))\?mode=crop.+width=(d+)&height=(d+) http://localhost:8888/unsafe/$2x$3/smart/$1

And in both cases, the result URL for the proxy is http://localhost:8888/unsafe/x/smart/$1 where should be http://localhost:8888/unsafe/300x300/smart/tdg/image.jpg

I have no clue why I can't fetch the width and height value from the query string, using group regex syntax.

已采纳解答

原帖链接 · Jeff Snider · CC BY-SA 3.0

The RewriteRule directive only matches on the path component, it does not include the query string. Try:

RewriteEngine On
RewriteCond %{QUERY_STRING} mode=crop.+width=(\d+)&height=(\d+)
RewriteRule ^\/(tdg.+\.(?:png|jpeg|jpg|gif)) http://localhost:8888/unsafe/%1x%2/smart/$1 [P]

Note the difference of the back-reference in the replacement when using RewriteCond. In order to use back-references from both places, use %N for those from RewriteCond and $N for those in the RewriteRule.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-10-17)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。