将"静态"子域别名限制为非HTML文件,否则重定向到"www"

Mar*_*cel 5 apache .htaccess mod-rewrite apache2

我为一个网站设置了几个"域别名",我将其用作无cookie的子域,因此static.domain.com/style.css提供相同的文件www.domain.com/style.css.

但是,如果有人试图访问static.domain.com/index.htm,则应将301重定向到www.domain.com/index.htm.mod_rewrite我认为根网页目录中的规则可行,但它们似乎不是.

<IfModule mod_rewrite.c>
    RewriteEngine On

    # "/res/all.20110101.css" => "/res/all.css"
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.+)\.(\d+)\.(js|css|png|jpg|jpeg|gif)$ $1.$3 [L]

    # Except for "static" sub-domains, force "www" when accessed without
    RewriteCond %{HTTP_HOST} .
    RewriteCond %{HTTP_HOST} !^www\.domain\.com [NC]
    RewriteCond %{HTTP_HOST} !^s-img\.domain\.com [NC]
    RewriteCond %{HTTP_HOST} !^static\.domain\.com [NC]
    RewriteRule (.*) http://www.domain.com/$1 [R=301,L]

    # If file requested is HTML, force "www" 
    <FilesMatch "\.(htm|html|php)$">
        RewriteCond %{HTTP_HOST} .
        RewriteCond %{HTTP_HOST} !^www\.domain\.com [NC]
        RewriteRule (.*) http://www.domain.com/$1 [R=301,L]
    </FilesMatch>

</IfModule>
Run Code Online (Sandbox Code Playgroud)

Mar*_*cel 0

在对 vbence 的答案进行了一些混乱之后,我偶然发现了一个更实用的解决方案,尽管我不确定它是否是最优化的解决方案。

<IfModule mod_rewrite.c>
   RewriteEngine On

   # Requests for "/res/all.20110101.css" serve up "/res/all.css", etc.
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^(.+?)\.([0-9]+)\.([a-z]+)$ $1.$3 [L]

   # If the hostname isn't www.domain.com AND requested file's extension
   # isn't in the filter list, redirect to the www.domain.com version.
   RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
   RewriteCond %{REQUEST_FILENAME} !\.(js|css|png|jpe?g|gif)$ [NC]
   RewriteRule (.*) http://www.domain.com/$1 [R=301,L]

</IfModule>
Run Code Online (Sandbox Code Playgroud)