Redirect from one path to another using htaccess
I have some urls like these:-
https://www.example.com/au/path1
https://www.example.com/sg/path1
https://www.example.com/ca/path1
and many more, I want to redirect these url to this type :-
https://www.example.com/au/path2
https://www.example.com/sg/path2
https://www.example.com/ca/path2
But I am not getting desired result, here is my code :-
RewriteEngine On
RewriteCond %{REQUEST_URI} path1
RewriteRule ^(.*)$ %{REQUEST_URI}/path2 [R=301,L]
You need to capture the prefix of the request uri and use that to make the redirection. Something like this:
RewriteRule ^(.*)/path1$ $1/path2 [R=301,L]
Update:
If you have a continuously changing set of aliases that you need to redirect, you might want to look into RewriteMap
. This module allows you to have different external sources to provide the map for the rewrites.
You can, for example have a text file with key, value pairs:
foo/bar /foo-new/bar
bar/foo /bar/foo-new
Then have a rewrite rule in combination with this map:
RewriteMap examplemap "txt:/path/to/file/map.txt"
RewriteRule "^(.*)$" "${examplemap:$1}"
Then you can make sure to update this file (in case from Drupal) whenever the map needs to change. Apache will look at the modification time of the file and flush the cache if it has changed.
You can also use an external application or use some other improved resources.
Another solution to redirect these urls one by one is Redirect directive of Apache mod_alias .
Try this in your root/.htaccess file :
RedirectPermanent /au/path1 /au/path2
RedirectPermanent /sg/path1 /sg/path2
RedirectPermanent /ca/path1 /ca/path2
You can change RedirectPermanent to RedirectTemp for temporary redirect.