Search code examples
.htaccessmod-rewritebackreference

Using backreference after RewriteCond in htaccess


I have:

RewriteCond %{HTTP_HOST} ^my.domain.com$ [NC]
RewriteRule ^(.*)$ index.php?q=search&keyword=$1

Input:

my.domain.com/foo_bar

I want:

index.php?q=search&keyword=foo_bar

But in fact:

index.php?q=search&keyword=index.php

I don't understand why. Please help me!


Solution

  • Your rewrite rule is actually rewriting twice, once for /foo_bar and second time for index.php as .* matches anything.

    You just need to add 2 conditions to stop rewrite for files and directories:

    # handle landing page
    RewriteCond %{HTTP_HOST} ^my\.domain\.com$ [NC]
    RewriteRule ^/?$ index.php?q=search [L,QSA]
    
    # handle /foo_bar
    RewriteCond %{HTTP_HOST} ^my\.domain\.com$ [NC]
    # If the request is not for a valid directory
    RewriteCond %{REQUEST_FILENAME} !-d
    # If the request is not for a valid file
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.+)$ index.php?q=search&keyword=$1 [L,QSA]