Reputation: 177
Having a wordpress website, I have a list of urls that I would like to have redirected to the root domain using the .htaccess file. Nothing fancy here just that when looking for this info I either found how to redirect all urls or specific folders but not a custom list of urls.
For example one of my urls is like this: example.com/path1/path2/ and I can easily add Redirect 301 /path1/path2/ http://example.com/
just under the RewriteEngine On
line in my .htaccess file.
By doing this, any other example.com/path1/path2/moreUrlPath/here will be redirected to example.com/moreUrlPath/here and adding another custom redirection line like this Redirect 301 /path1/path2/moreUrlPath/here http://example.com/
will have no effect whatsoever.
Bottomline, having a list of urls, how can I permanently redirect them to the root domain?
Upvotes: 0
Views: 729
Reputation: 2972
Use mod_rewrite and a RewriteRule
instead of Redirect
.
The RewriteRule uses a regular expression to match the URL, so you can say
RewriteRule ^path1/path2/$ http://example.com/ [R=301,L]
to match exactly "/path1/path2/" (you are always beneath / when working in the .htaccess, so the leading / isn't included). ^
stands for "start matching at the beginning" and $
means "and stop at the end", so there can't be anything after path2/. This allows you to be very specific, e.g. you could go for
RewriteRule ^path1/path2/a$ http://example.com/ [R=301,L]
RewriteRule ^path1/path2/aa$ http://subdomain.example.com/ [R=301,L]
When you don't need to be specific, and you want to redirect everything under a certain path, you use an open ended match:
RewriteRule ^path1/path2/ http://example.com/ [R=301,L]
This will redirect everything beneath /path1/path2/ to the root directory, and it will NOT care about what comes after path2/, so /path1/path2/test/
will not redirect to http://example.com/test/ as it would with Redirect
.
You can do that too, though, by using backreferences and matching certain parts with parentheses, e.g.
RewriteRule ^path1/path2/(.*) http://example.com/$1 [R=301,L]
Which will then redirect /path1/path2/ to http://example.com/, but /path1/path2/test/ to http://example.com/test/.
Upvotes: 0