[.htaccess] htaccess redirect if URL contains a certain string

How would I write a .htaccess redirect rule if the URL contains a certain word?

e.g. if it contains foobar then redirect to index.php

This question is related to .htaccess

The answer is


If url contains a certen string, redirect to index.php . You need to match against the %{REQUEST_URI} variable to check if the url contains a certen string.

To redirect example.com/foo/bar to /index.php if the uri contains bar anywhere in the uri string , you can use this :

RewriteEngine on

RewriteCond %{REQUEST_URI} bar
RewriteRule ^ /index.php [L,R]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/foobar/i$ index.php [NE,L]

RewriteRule ^(.*)foobar(.*)$ http://www.example.com/index.php [L,R=301]

(No space inside your website)