Matt Irvine
Matt Irvine

Reputation: 33

mod_rewrite to shorten url files path

I am having a bit of difficulty getting mod_rewrite to do what I need it to do.

We have a group of virtual subdomains in a Drupal install. So, academics.univ.edu, about.univ.edu, etc are all part of the same core Drupal install.

File access currently is academics.univ.edu/sites/all/academics/files/myfile.jpg. However this path will also work as about.univ.edu/sitse/all/about/files/myfile.jpg or any other valid subdomain.

We'd like to use mod_rewrite to accept academics.univ.edu/files/myfile.jpg and deliver the file from the above location.

Here's what I've tried:

RewriteCond %{REQUEST_URI} ^(about|academics|bursar|calendar)\.univ\.edu\/files\/(.*)$ [NC]
RewriteRule ^/sites/all/files/$1/$2 [L,NC]

I'm probably going about this the wrong way, but I wanted to check on it. I can get the subdomains to work by making separate rules using HTTP_HOST, but I wanted less rules in the file. Also, I can't get HTTP_HOST to work on sites that exist as a subdirectory in a subdomian. For instance, undergrad.univ.edu/biology/files/myfile.jpg should deliver /sites/all/biology/files/myfile.jpg

Upvotes: 3

Views: 310

Answers (1)

Jon Lin
Jon Lin

Reputation: 143886

You can't match a host in the %{REQUEST_URI}, you need to use %{HTTP_HOST}, then use the %1 backrefernce to access that match. The actual URI can be matched in the rule itself. Something like this:

RewriteCond %{HTTP_HOST} ^(about|academics|bursar|calendar)\.univ\.edu$  [NC]
RewriteRule ^files/(.*)$ /sites/all/files/%1/%2 [L,NC]

The %1 references the match (about|academics|bursar|calendar) in the RewriteCond and the $1 references the match (.*) in the RewriteRule. So that example will take a request to http://about.univ.edu/files/foo.html and rewrite the request to /sites/all/files/about/foo.html.

Also, if this is in a virtualhost or server config, you need a "/" in between "^" and "files" in the RewriteRule.

Upvotes: 2

Related Questions