I have new website done for one client, and now I am doing all redirects in .htaccess file. I was bit confused regarding the source URL part in lines below. Are these two lines works same way?
Redirect 301 /shop/contact-us http://www.example.com/contact-us/
Redirect 301 /shop/contact-us/ http://www.example.com/contact-us/
If you want to redirect /shop/contact-us
with a number of optional trailing slashes to http://www.example.com/contact-us
, then the Redirect
directive is not very appropriate. Use RedirectMatch
directive instead:
RedirectMatch 301 "^/shop/(contact\-us)/?" http://www.example.com/$1/
where
^
is an anchor meaning "beginning of the line";/?
matches zero or one slash character;(contact\-us)
is a capturing group (referenced by $1
)Note, the regular expression matches only the prefix, since only the ^
anchor is used. You can use the $
(end of the line) anchor in order to make the expression stricter, e.g.:
RedirectMatch 301 "^/shop/(contact\-us)/*$" http://www.example.com/$1/
where /*
means zero or more slashes.
The source urls that you have listed are unique and different because one has a trailing slash.
Actually order can matter with mod alias.
If we have the following:
Redirect 302 '/foo/' 'http://example.com/foo.php'
Redirect 302 '/foo' 'http://example.com/bar.php'
And visit /foo/
we'll get a temporary redirect to http://example.com/foo.php
. If we visit /foo
we'll get a temporary redirect to http://example.com/bar.php
.
But if we change the order:
Redirect 302 '/foo' 'http://example.com/bar.php'
Redirect 302 '/foo/' 'http://example.com/foo.php'
And visit /foo/
, oddly the first pattern /foo
will match and you'll end up at http://example.com/bar.php
!
I tend to write more specific (longer source urls first).
Sometimes I get some quite bizarre results using mod alias redirects. So end up writing specific pattern matches using RedirectMatch or use mod rewrite instead.
In your case it looks as if you want both:
/shop/contact-us
and
/shop/contact-us/
To redirect to the same url. So you could simply omit one rule and just use:
Redirect 301 /shop/contact-us http://www.example.com/contact-us/
But perhaps historically you have used both patterns to access the same or different resources, so it may be better to list both (but change the order).