Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 853
Marcel Avatar asked Nov 06 '22 01:11

Marcel


1 Answers

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]
like image 188
vbence Avatar answered Nov 09 '22 14:11

vbence