Restrict "static" sub-domain aliases to non-HTML files, otherwise redirect to "www"
I've set up a couple of "domain aliases" for a website which I'm using as cookie-less sub-domains, so static.domain.com/style.css
serves the same file as www.domain.com/style.css
.
However, if someone tries to access static.domain.com/index.htm
they should be 301 redirected to www.domain.com/index.htm
. The mod_rewrite
rules I have in the root web directory I thought would work but they don't seem to be.
<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>
This will redirect every request which does not go for static files:
RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
RewriteCond %{REQUEST_FILENAME} !\.(js|css|png|jpg|jpeg|gif)$ [NC]
RewriteRule (.*) http://www.domain.com/$1 [R=301,L]
It reads:
- IF hostname is not www.domain.com
- AND requested file does not end with an allowed extension
- Then redirect to the master (www) domain
Also for your versioning (you need the non-greedy (.+?)
because .+
would eat your whole string and there would be no match for the pattern):
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+?)\.([0-9]+)\.([a-z]+)$ $1.$3 [L]
After messing around a bit with vbence's answer, I stumbled upon a more functional solution, although I'm not sure if it's the most optimised one.
<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>
精彩评论