I have a anchor tag in my html content like this href="/abcd/test.html"
.
and this is in a lot of places in my html for a list of some results.
I need to append all these URLs that are in "href" by appending a prefix.
For example: /abcd/test.html
should be dynamically changed as newprefix/abcd/test.html
If i have another one like /xyz/some.html
then this should be changed as newprefix/xyz/some.html
I have explored different solutions over the internet and I have not found something that would fit my problem.
CodePudding user response:
To implement an external redirect to prepend /newprefix
to these requests you could do something like the following near the top of the root .htaccess
(or server config).
For example:
RewriteEngine On
RewriteRule ^[^/] /[^./] \.html$ /newprefix/$0 [R=302,L]
The above will redirect requests for /abcd/test.html
or /xyz/some.html
to /newprefix/abcd/test.html
and /newprefix/xyz/some.html
respectively. Anything that matches the pattern /<something>/<file>.html
.
$0
is a backreference that contains the URL-path that is matched by the RewriteRule
pattern.
Note that this is not "url-rewriting" since you stated in comments that you do not want to "hide" the /newprefix
part of the URL from your users. An external redirect is therefore the only solution if you are intending to use Apache / mod_rewrite (as tagged).
Aside: This is not particularly good for SEO, your users or your server since the user is externally redirected everytime they click one of your links, potentially doubling the number of requests that hit your server and slowing your users.