In apache, how can I redirect to homepage in case if you will go to exact string, but everything behind this string should be displayed normally, no redirect.


http://example.com/STRING -> go to homepage
http://example.com/STRING_PAGE -> go to http://example.com/STRING_PAGE

I tried

Redirect 301 /STRING http://example.com/

But in this case page is redirected to homepage too, for example in case of http://example.com/STRING_PAGE.


1 Answer 1


Instead of using mod_alias and its Redirect directive, you can use mod_rewrite using a RewriteRule with a RewriteCond:

RewriteEngine On
RewriteRule ^/?STRING       / [R=301,NC,L]

This redirects all requests starting with /STRING or STRING, but not starting with /STRING_PAGE. The match for a leading slash ^/ is needed if the rule is defined in a VirtualHost context and must be omitted in a <Directory/> or .htaccess context. It's just easier to use /? to make it optional, so the rule can be used in both.

The NC flag is used for a case-insensitive match and L stops processing any following rules.

You need to enable mod_rewrite (sudo a2enmod rewrite) to use this.

  • Thanks, yes, at the end, I used Rewrite.
    – genderbee
    Feb 17, 2020 at 13:38
  • Although this doesn't match the "exact name", it matches everything that starts /STRING except /STRING_PAGE. It would still redirect /STRING_ANOTHERPAGE, etc.
    – MrWhite
    Feb 17, 2020 at 20:54
  • 1
    @MrWhite Correct and I overlooked the "exact string" in the question. For an exact match RewriteRule ^/?STRING$ / [R=301,NC,L] should be sufficient (without RewriteCond).
    – Freddy
    Feb 17, 2020 at 21:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.