Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect based on the beginning of the path

I'm building a Laravel project. The project itself has a "legacy" version with a whole different structure. It's logged that some users are trying to access a file that is not found in the new environment.

For a quick "fix", we want to redirect paths like

  • /media/22044/blablabla.pdf to /en/press

The quick solution is to use

Redirect 301 /media/22044/blabla.pdf /en/press

But we want the path behind /media/ to be dynamic. I'm new with .htaccess stuff. Is there a way to do it?

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_URI} !^public
RewriteRule ^(.*)$ public/$1 [L]

# this one works, but not dynamic
#Redirect 301 /media/2336/blabla.pdf /en/press

# failed experiments
#Redirect 301 (\/media)(.*)$ /en/press
#Redirect 301 ^/media/(.*)$ /en/press
#RewriteRule ^/media/(.*) /en/press [R=301,NC,L]
Redirect 301 /media/(.*) /en/press
</IfModule>
like image 647
Aldo Adhi Avatar asked Jan 24 '26 14:01

Aldo Adhi


1 Answers

You need to use a mod_rewrite RewriteRule directive (not Redirect) before your existing rewrite.

For example:

RewriteEngine on

# Redirect "/media/<anything>" to "/en/press"
RewriteRule ^media/ /en/press [R=301,L]

# Rewrite all requests to the "/public" subdirectory
RewriteCond %{REQUEST_URI} !^public
RewriteRule ^(.*)$ public/$1 [L]

The Redirect directive uses simple prefix-matching, not a regex. But is also processed later in the request.

And note that the URL-path matched by the RewriteRule pattern does not start with a slash, unlike the Redirect directive.

like image 125
MrWhite Avatar answered Jan 27 '26 12:01

MrWhite



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!