tags:

views:

48

answers:

4

I need to rewrite url with rule like below

RewriteRule ^files/([a-z0-9-\.]+)$ files/domain.com/$1

domain.com is current host name. It is dynamic (don't ask why plz). So I can not do like this. Anyway, how I can get current host name and put it like this:

RewriteRule ^files/([a-z0-9-\.]+)$ files/{{ current host name with out www. }}/$1
+3  A: 

%{HTTP_HOST} will give you the requested host name.

I can't test right now whether it can be used in a RewriteRule, but I think it can.

Pekka
It return www. If host name include www. How can I solve it?
complez
+1  A: 

I think this might do the trick for you:

RewriteRule ^files/([a-z0-9-\.]+)$ files/%{SERVER_NAME}/$1
RewriteRule ^files/www\.([^/]+)/([a-z0-9-\.]+)$ files/$1/$2

(The second line removes any www. from the domain.)

Justin Russell
+3  A: 
RewriteCond %{HTTP_HOST} ^(www\.)(.*)$
RewriteRule ^files/(a-z0-9-\.]+)$ files/%2/$1

Can't test either, but it should be something like this. (www\.) makes sure with or without www it works, then the (.*) part in the HTTP_HOST captures the rest of the domain. By using %2 this domain is later re-used in the new request.

Litso
I think it should be RewriteCond %{HTTP_HOST} ^(www\.)?(.*)$
complez
You're right, my bad.
Litso
+3  A: 

As already mentioned, %{HTTP_HOST} contains the value of the Host header field.

You can use the following to always get only the last two domain levels:

RewriteCond %{HTTP_HOST} ([^.]+\.[^.]+)$
RewriteRule ^files/([a-z0-9-\.]+)$ files/%1/$1
Gumbo
This one is the best, it's probably (a bit) faster than both, and also more secure than mine.
Litso
Very nice solution, but be cautious if you may run across a domain with more than two significant levels (for example, blog.example.com).
Justin Russell
Hmm, hadn't thought of that. This one will load /domain.com/ regardless of the subdomain, mine would load /blog.subdomain.com/
Litso
RewriteCond %{HTTP_HOST} ([^.]+\.[^.]+)$RewriteRule ^files/([a-z0-9-\.]+)$ files/%1/files/$1RewriteRule ^templates/([a-z0-9_ \.-]+)$ files/%1/templates/$1 When I put a new rule line for templates, both won't work any more include rule 1 (files)?
complez
@complez: `RewriteCond %{HTTP_HOST} ([^.]+\.[^.]+)$ RewriteRule ^(files|templates)/([a-z0-9-\.]+)$ files/%1/$1/$`
Gumbo