2

我有一个像这样的文件目录的网站

/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/200x150http://example.com/images/200x180. 从两个 URL 我们知道第一个图像存在,/storage/200/200x150.png但不存在第二个。

所以,我想为此写.htaccess(理论上在这里)。

Rewrite Condition /storage/{width}/{widthxheight}.png existed?
Rewrite Rule {output the image}
Rewrite Failed {go to /somedir/failed.php}

我怎样才能做到这一点?

4

2 回答 2

1

从您的示例中,图像请求的典型 URL 如下所示

http://example.com/images/WidthxHeight

其中WidthHeight是变量并且images是固定字符串。

典型的替换 URL 应该是这样的:

http://example.com/storage/Width/WidthxHeight.png

whereWidthHeight是从传入 URL 传递的参数,而storagepng是固定字符串。

你可以试试这个:

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]

于 2013-03-16T21:44:07.970 回答
0

根据当前 .htaccess 的设置方式,您可以将所有不存在的文件路由到 failed.php:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . /failed.php [L]
于 2013-03-16T17:30:42.323 回答