How to redirect the root of a directory in .htaccess without also redirecting all the contents?

How to redirect the root of a directory in .htaccess without also redirecting all the contents? - .htaccess files are extremely useful in many cases for users who either do not have root permissions or for users who simply aren't comfortable in making changes in their web server's configuration file. Trying to debug .htaccess not working isn't always the easiest thing to do, however, hopefully by checking the discuss below mentioned about htaccess, redirects, url, directory, .htaccess common problems as well as the troubleshooting tips, you'll have a better grasp on what you may have to modify to get your .htaccess file running smoothly.Problem :


I have two specific URL which are being redirected with 301 redirect in my .htaccess file like below:



redirect 301 /old-url-1/ http://www.domain.com/new-url-3/
redirect 301 /old-url-2/ http://www.domain.com/new-url-3/


Now problem is with URL structure like this:



http://www.domain.com/old-url-1/sub-url/ or http://www.domain.com/old-url-2/sub-url/ which is not getting to desired path on redirected url to
http://www.domain.com/old-url-1/sub-url/.



How can I only match /old-url-1/ part, and redirect in that case, in all other cases just follow original path like /old-url-1/sub-url/?



**Desired effect is like this:
If someone goes to:
http://www.domain.com/old-url-1/ redirect visitor to http://www.domain.com/new-url-3/, but if someone goes to http://www.domain.com/old-url-1/sub-url/keep visitor on that URL, and don't redirect to http://www.domain.com/new-url-3/sub-url.


Solution :

The key to redirect only exact URL match is to tell redirectMatch to match only exactly URL which is easy achieved with regex according to httpd.apache.org, where description says:




Description: Sends an external redirect based on a regular expression match of the current URL
Syntax: RedirectMatch [status] regex URL




In my case,



redirect 301 /old-url-1/ http://www.domain.com/new-url-3/


Becames



RedirectMatch 301 ^/old-url-1/$ http://www.domain.com/new-url-3/


Where ^matches the beginning of URL, and $ to match the end of URL.



So my rule only will match old-url-1, and not old-url-1/sub-url or some another odl-url-1/some-sub-path.


Additionally, if you would like to do some further testing, give the htaccess tester tool a try. It allows you to specify a certain URL as well as the rules you would like to include and then shows which rules were tested, which ones met the criteria, and which ones were executed.

Comments

Popular posts from this blog

Rewrite in Mediawiki, remove index.php, .htaccess

.htaccess rewrite wildcard folder paths from host

Using .htaccess to set a cookie and 301 redirect