从您的示例中,图像请求的典型 URL 如下所示
http://example.com/images/WidthxHeight
其中Width
和Height
是变量并且images
是固定字符串。
典型的替换 URL 应该是这样的:
http://example.com/storage/Width/WidthxHeight.png
whereWidth
和Height
是从传入 URL 传递的参数,而storage
和png
是固定字符串。
你可以试试这个:
Options +FollowSymlinks -MultiViews
RewriteEngine On
RewriteBase /
# Make sure the request is for an image file
RewriteCond %{REQUEST_URI} ^/images/([^x]+)x([^/]+)/? [NC]
# Don't want loops
RewriteCond %{REQUEST_URI} !storage [NC]
# Make sure the file exists
RewriteCond %{REQUEST_FILENAME} -f
# If all conditions are met, rewrite
RewriteRule .* /storage/%1/%1x%2.png [L]
## Else, map to failed.php
RewriteCond %{REQUEST_URI} !storage [NC]
RewriteCond %{REQUEST_URI} !failed\.php [NC]
RewriteRule .* /somedir/failed.php [L]
更新
对于带有一个参数和没有参数的传入 URL 有 2 个附加规则。
Options +FollowSymlinks -MultiViews
RewriteEngine On
RewriteBase /
## New option 1
## Check if the request has any parameter
RewriteCond %{REQUEST_URI} !storage [NC]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^images/?$ /storage/200/200x200.png [L,NC]
## New option 2
## Check if the request has only 1 parameter
RewriteCond %{REQUEST_URI} !x [NC]
RewriteCond %{REQUEST_URI} !storage [NC]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^images/([^/]+)/?$ /storage/$1/$1x$1.png [L,NC]
## Check if the request has 2 parameters
RewriteCond %{REQUEST_URI} !storage [NC]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^images/([^x]+)x([^/]+)/? /storage/$1/$1x$2.png [L,NC]
## Else, map to failed.php
RewriteCond %{REQUEST_URI} !storage [NC]
RewriteCond %{REQUEST_URI} !failed\.php [NC]
RewriteRule .* /somedir/failed.php [L]
对于永久和可见的重定向,将 [L,NC] 替换为 [R=301,L,NC]