By Brendo Ross
Hi lads,
I’m in need of some help with a tricky Apache rewrite situation I’m facing. I have multiple subdomains and subdirectories with various access requirements, and I want to create a rewrite rule that satisfies a couple of conditions.
Basically, if :
subdomain.example.com
/files/
..pdf
or .jpg
.public_
prefix.If all the above conditions are met, the request should be redirected to a separate domain https://public-files.example.net/
.
I’ve tried the following rewrite rule:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^subdomain\.example\.com$
RewriteCond %{REQUEST_URI} ^/files/public_.*\.(pdf|jpg)$
RewriteRule ^/files/public_(.*)\.(pdf|jpg)$ https://public-files.example.net/$1.$2 [R=301,L]
ofcourse with my domains but it doesn’t work. I believe it might be conflicting with other rewrite rules in my configuration.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Accepted Answer
Heya,
I’ve looked into your rewrite rule, and it seems mostly correct. However, there are a couple of things that could be improved to make it work as expected. Here’s an updated version of the rule:
- RewriteEngine On
- RewriteCond %{HTTP_HOST} ^subdomain\.example\.com$
- RewriteRule ^/files/public_(.+)\.(pdf|jpg)$ https://public-files.example.net/public_$1.$2 [R=301,L]
I removed the RewriteCond
for the %{REQUEST_URI}
because it’s not necessary since the RewriteRule pattern will only match if the conditions are already met. I also simplified the RewriteRule
pattern and included the public_
prefix in the replacement URL.
I’ve tested it on my end and it works as you’ve described but do let me know how it goes with you
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.