Report this

What is the reason for this report?

Apache rewrite rule for specific subdomain and file types

Posted on May 1, 2023

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.



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!

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.
0

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

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.