Search code examples
.htaccesshttp-redirect

How to replace a specific word from a specific position of URL using htaccess


I want to replace a word from url. I have tried many code but. not working

For e.g. I have a URL : https://www.example.com/blog/single/how-to-start-single-app

Want to redirect to URL - https://www.example.com/blog/post/how-to-start-single-app

tried with the below rule

RewriteRule ^(.*)single(.*)$ $1post$2 [R=301,L] 

but it replace all the single word of url into post.


Solution

  • Your rule does make sense, but you'd have to be more precise.

    Either follow a strategy based on an absolute path in a rule you implement on top level:

    RewriteRule ^/?blog/single/(.+)$ /blog/post/$1 [R=301,L]
    

    Or you do the same in a relative manner inside the "blog" folder:

    RewriteRule ^single/(.+)$ post/$1 [R=301,L]
    

    The important bit in both approaches is to anchor the pattern to the beginning of the subject by using the ^ special char.

    I personally prefer the first strategy. If possible you should even implement such rules in the actual http server's host configuration if you have access to that. Instead of using multiple distributed configuration files.