How to Redirect URL Using .htaccess if Contains Specific Word (.html)

Published on January 20, 2020 28 sec read

In this tutorial, I’m going to share how to redirect URL using .htaccess if it contains specific word. Let’s think our blog URLs contain .html end of the URL. We’re going to redirect the .html URLs to without .html.

The Solution

We can do this using .htaccess rewrite rule. Open .htaccess file and write the rule like this:

RewriteEngine On

# check if url contains .html and then redirect to without .html link
RewriteRule (.*).html$ /$1 [R=301,L]

Let’s see another example. If URL contains foobar we’ll redirect the URL to index.php. Here’s the rule:

RewriteEngine on

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

We also can write the rule like this:

RewriteEngine on

RewriteRule ^(.*)foobar(.*)$ [L,R=301]

I hope this article will help you. 🙂

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.

Hey, I'm Md Obydullah. I build open-source projects and write article on Laravel, Linux server, modern JavaScript and more on web development.