Home > Net >  htaccess redirect based on the beginning of the path
htaccess redirect based on the beginning of the path

Time:01-30

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/ is 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>

CodePudding user response:

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.

CodePudding user response:

With your shown samples and attempts please try following .htaccess rule file. Please make sure to clear your browser cache before testing your URLs.

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

###new redirect here...
RewriteCond %{THE_REQUEST} \s/.*/media/22044/blablabla\.pdf\s [NC]
RewriteRule ^  /en/press? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(en/press)/?$ media/22044/blablabla\.pdf [NC,L]
</IfModule>
  • Related