使用.htaccess进行选择性网址重定向

时间:2016-12-13 11:44:38

标签: php .htaccess redirect

我有一个包含大量图片和静态内容的现有网站。我现在已经注册了MaxCDN,需要将静态内容重定向到他们的cdn。

我希望有一个htaccess规则来检测array('css', 'js', 'jpg', 'jpeg', 'png' 'gif','pdf')之类的文件扩展名并重定向到cdn网址。

示例: 普通网址:https://www.example.com/uploads/slider/1470903158.jpg CDN网址:https://www.cdn.com/uploads/slider/1470903158.jpg

我已经为我的区域定义了CDN网址。我会使用核心base_url()覆盖来执行相同的功能,但不幸的是网站不在CI中,重新开始是不可行的。我认为用.htaccess做这件事在我目前的情况下是最好的选择。不幸的是,当谈到.htacces时我几乎一无所知。

这是我当前的.htaccess文件

<IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteBase /

        # Removes index.php from ExpressionEngine URLs
        RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
        RewriteCond %{REQUEST_URI} !/system/.* [NC]
        RewriteRule (.?)index\.php/(.*) /$1$2 [R=301,NE,L]

        # Directs all EE web requests through the site index file
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ /index.php/$1 [L]
</IfModule>


# BEGIN Expires
<ifModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 seconds"
ExpiresByType text/html "access plus 1 seconds"
ExpiresByType image/gif "access plus 2592000 seconds"
ExpiresByType image/jpeg "access plus 2592000 seconds"
ExpiresByType image/png "access plus 2592000 seconds"
ExpiresByType text/css "access plus 604800 seconds"
ExpiresByType text/javascript "access plus 216000 seconds"
ExpiresByType application/x-javascript "access plus 216000 seconds"
</ifModule>
# END Expires


#The following line is enough for .js and .css
    AddOutputFilter DEFLATE js css

    #The following line also enables compression by file content type, for the following list of Content-Type
    AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml

    #The following lines are to avoid bugs with some browsers
    BrowserMatch ^Mozilla/4 gzip-only-text/html
    BrowserMatch ^Mozilla/4\.0[678] no-gzip
    BrowserMatch \bMSIE !no-gzip !gzip-only-text/html 
   Header append Vary: Accept-Encoding

1 个答案:

答案 0 :(得分:2)

您可以将此重定向规则用作第一条规则:

RewriteEngine On

RewriteRule ^.+\.(?:jpe?g|gif|pdf|css|js)$ https://www.cdn.com%{REQUEST_URI} [L,R=301,NC,NE]

请注意,虽然此规则将完全按照问题运行并执行,但它不会解决CDN的问题。 CDN将仅捕获具有http报头200的内容而不重定向(301)。所以即使你启用了这个机会取决于你的CDN提供商网站不会加载,或者即使加载它也会破坏CDN的目的,因为如果所有请求都转到你的原点,然后被重定向到CDN数据中心那么就没有了提高速度。