Asked  7 Months ago    Answers:  4   Viewed   48 times

After a site redesign, I've got a couple of pages that need to be redirected. Everything is staying on the same domain, just a couple of things have been reorganised and/or renamed. They are of the form:

/contact.php

is now:

/contact-us.php

Using the .htaccess file, I've added this line, which is the one I find recommended most:

RedirectMatch 301 /contact.php /contact-us.php

This is mostly fine - it does the job - the problem is, it also redirects:

  • /team1/contact.php
  • /non-existant-folder/contact.php

Is there a way of specifying that I only want to redirect the contact.php in the root?

 Answers

41

RedirectMatch uses a regular expression that is matched against the URL path. And your regular expression /contact.php just means any URL path that contains /contact.php but not just any URL path that is exactly /contact.php. So use the anchors for the start and end of the string (^ and $):

RedirectMatch 301 ^/contact.php$ /contact-us.php
Wednesday, March 31, 2021
 
Zigglzworth
answered 7 Months ago
84

It appears that the only answer to this one at the moment is to not use FastCGI on IIS7 when using PHP (because of a bug in FastCGI) - which is rubbish because it's very quick. Using isapi allows the 301 redirects to work as they should, but it's not as fast.

Saturday, May 29, 2021
 
PHLAK
answered 5 Months ago
76

You can't put query string parameters in the source URI path of the Redirect directive. You'll have to use mod_rewrite's %{QUERY_STRING} variable for that:

RewriteEngine On
RewriteCond %{QUERY_STRING} ^id=123$
RewriteRule ^/?product.php$ http://website.com.au/product_123.php? [L,R=301]

Or to make it more general:

RewriteEngine On
RewriteCond %{QUERY_STRING} ^id=([^&]+)
RewriteRule ^/?product.php$ http://website.com.au/product_%1.php? [L,R=301]
Thursday, July 29, 2021
 
skrilled
answered 3 Months ago
98

You can tweak your regex to match BaTa anywhere like this:

RewriteEngine on
RewriteRule ^(.+?/)?BeTa(?:/(.*))?$ /$1$2 [NC,R=301,L]
Tuesday, August 31, 2021
 
Paul Renton
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :