2

I have a bunch of old files prefixed with old- (e.g. old-abcde.php). I need an htaccess rule to set up a 301 redirect so that any request for a file starting with old- goes to its corresponding new version (e.g. abcde.php).

To be clear, I have many files, not just one, so I can't do a literal filename match. I basically just need to strip off the old- from the request and redirect to the version without it.

I know I probably just need a simple regular expression, but I'm not good at writing them. Can anyone provide assistance?

1

Try ModRewrite:

RewriteEngine On
RewriteRule old-(.*)$ $1 [NE,R]

This sends an 301 to the browser and redirects it.

  • This actually sends a 302 (temporary) redirect - the default when only the bare R flag is used. You need to explicitly include the status code, ie. R=301, if you want a 301 (permanent) redirect. The pattern old-(.*)$ also does not only match files that start "old-", it would also match "penfold-abc.php". You need the start of string anchor ^. – MrWhite Jun 2 '16 at 22:12
1

I would use this in the .htaccess file :

RewriteEngine on
RewriteRule old-(.*)$ $1 [L,R=301]

Add QSA between the brackets if you have to keep the additional query string (like ?ID=xxxxx). Specify R=301 to make a 301 redirect and specify the redirect is permanent.

  • You would need to prefix the RewriteRule pattern with the start-of-string-anchor (^) to match URLs that start "old-", otherwise you might match too much. The end-of-string-anchor ($) is not required. The QSA flag would not be required here. Any query string on the request is passed through to the substitution by default. The QSA would only be required if you were including a query string in the substitution and you needed to merge the query string from the request. – MrWhite Jun 2 '16 at 22:17
0

Using mod_rewrite in the .htaccess file in the document root:

RewriteEngine On
RewriteRule ^(.+/)?old-(.*) /$1$2 [R=301,L]

This will handle old- files in the document root and anywhere on the filesystem (not explicitly stated in your question, but the other answers assume these files are all located in the document root). It assumes that abc.php is in the same directory as old-abc.php.

The slash prefix on the substitution (ie. /$1$2) is required in the case of an external redirect, otherwise the directory prefix will be added and the redirect will break, exposing your directory structure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.