Harsh Sharma Harsh Sharma - 1 year ago 54
PHP Question

Need help regarding .htaccess rewrite rule for query string urls with dynamic subdirectory

I am working on a project and I am stuck with some

rewrite rule which is not working & I tried many things but no luck, so please help me.

Here is what I am doing:

when I open:

it should have to read the file
from root directory & work like this:

it's properly getting subdirectory, but not getting keywords and location data.

Here is my

Options +FollowSymlinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^domain.com [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [L,R=301]
RewriteRule ^(.*)/(.*)-ad(.*).html ad.php?countrycode=$1&title=$2&id=$3 [NC]
RewriteRule ^(.*)/$ country.php?countrycode=$1 [NC]
RewriteRule ^(.*)/(.*)-author\.html author.php?countrycode=$1&q=$2 [NC]
RewriteRule ^(.*)/(.*)-author/currentpage=(.*) author.php?countrycode=$1&q=$2&currentpage=$3 [NC]
RewriteRule ^(.*)/search\.html?keyword=(.*)&location=(.*) search.php?countrycode=$1&keyword=$2&location=$3 [NC,L]
RewriteRule ^(.*)/search\.html$ search.php?countrycode=$1 [NC,L]
RewriteRule ^(.*)/latest\.html$ latest.php?countrycode=$1 [NC,L]
RewriteRule ^(.*)/submit\.html$ submit.php [NC,L]
RewriteRule ^error\.html$ error.php [NC,L]
ErrorDocument 400 /error.html
ErrorDocument 401 /error.html
ErrorDocument 403 /error.html
ErrorDocument 404 /error.html
ErrorDocument 500 /error.html

Answer Source

The relevant rule is

RewriteRule ^(.*)/search\.html$ search.php?countrycode=$1 [NC,L]

Usually RewriteRule keeps an existing query string, unless you add one yourself

Modifying the Query String

By default, the query string is passed through unchanged. You can, however, create URLs in the substitution string containing a query string part. Simply use a question mark inside the substitution string to indicate that the following text should be re-injected into the query string. When you want to erase an existing query string, end the substitution string with just a question mark. To combine new and old query strings, use the [QSA] flag.

To keep the previous query string, you must add the QSA|qsappend flag

RewriteRule ^(.*)/search\.html$ search.php?countrycode=$1 [NC,L,QSA]

This rewrites search.html unconditionally.

If you want to rewrite it only when the request contains the query string keyword=xyz&location=alabama, you must prefix the rule with a RewriteCond with %{QUERY_STRING}

RewriteCond %{QUERY_STRING} keyword=.+?&location=.
RewriteRule ^(.*)/search\.html$ search.php?countrycode=$1 [NC,L,QSA]

P.S. At the beginning, you write search.php?directory=us&..., but in the rules you have search.php?countrycode=.... Adjust the rules accordingly.