Search code examples
laravelapache.htaccessmod-rewrite

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>

Solution

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