简体   繁体   中英

Redirect custom urls to root domain using htaccess

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?

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, eg 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, eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM