Home > Blockchain >  htaccess rewrite find part of the slug and remove it
htaccess rewrite find part of the slug and remove it

Time:12-18

I have posts like so:

http://example.com/blog/post-title

I want to convert this to

http://example.com/post-title

Using htaccess

I tried:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com/blog/([^\s\?] )\s [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301,NC]

CodePudding user response:

In this situation, you can indicate two capture groups (using parentheses) and only return the second of the two groups.

Example:

<IfModule mod_rewrite.c>

RewriteEngine On

RewriteRule ^(blog)/(. ) http://example.com/$2

</IfModule>

The rewrite rule works as follows:

If...

  • the url starts with blog
  • followed by /
  • followed by at least one or more characters

then rewrite the URL so that the domain is followed by a / and then the one or more characters that were captured in the second capture group.

N.B. You won't need an [R=301] flag since providing a full redirect (ie. a redirect starting with the http:// or https:// protocol) implicitly indicates that this will be a 301 Redirect.

  • Related