Question

Apache rewrite rule for specific subdomain and file types

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 :

  • the request comes from the subdomain subdomain.example.com
  • the requested URL path starts with /files/.
  • the file extension is .pdf or .jpg.
  • the filename starts with a 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.


Submit an answer


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!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

KFSys
Site Moderator
Site Moderator badge
May 1, 2023
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:

  1. RewriteEngine On
  2. RewriteCond %{HTTP_HOST} ^subdomain\.example\.com$
  3. 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

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel