我有一个像这样的文件目录的网站
/index.php (home page)
/storage (file storage directory)
/800 (800 pixel width dir)
/800x200.png
/800x350.png
....
/200 (200 pixel width dir)
/200x150.png
/200x185.png
...
....
/css
/style.css
/images
/logo.png
/jscript
/autoload.js
现在,用户将发出请求http://example.com/images/200x150
或http://example.com/images/200x180
。从两个网址我们知道第一张图片存在于/storage/200/200x150.png
中,但不存在于第二张图片中。
所以,我想为此写.htaccess
(理论上这里)。
Rewrite Condition /storage/{width}/{widthxheight}.png existed?
Rewrite Rule {output the image}
Rewrite Failed {go to /somedir/failed.php}
我该怎么做?
答案 0 :(得分:1)
从您的示例中,图像请求的典型网址就像这样
http://example.com/images/WidthxHeight
其中Width
和Height
是变量而images
是固定字符串。
典型的替换网址应该是这样的:
http://example.com/storage/Width/WidthxHeight.png
Width
和Height
是从传入网址传递的参数,而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]
答案 1 :(得分:0)
取决于.htaccess当前的设置方式,您可以将所有非现有文件路由到failed.php:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . /failed.php [L]