Home > Software engineering >  How to replace a specific word from a specific position of URL using htaccess
How to replace a specific word from a specific position of URL using htaccess

Time:11-25

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.

CodePudding user response:

You can do it using REGEX:

RedirectMatch  301 /old-slug/(.*) /newslug/$1

In your case

RedirectMatch  301 /blog/single/(.*) /blog/post/$1

Here,

(.*) is a wildcard that matches anything that appears after /old-slug/ and saves it to use in the target URL and $1 outputs the first wildcard from source URL expression.

CodePudding user response:

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.

  • Related