skip to Main Content

Is it possible for me to add an htaccess rule for a search page so that it will work with and without query parameter. I ll add the example below

Actual file is www.mysite.com/search.php

Below 2 links should work for me

  1. www.mysite.com/search/loremipsum

  2. www.mysite.com/search/?query=loremipsum

The rule I have added on htacess is given below

RewriteCond %{QUERY_STRING} ^$
RewriteRule ^search/?$ search.php? [L]
RewriteRule ^search/([^/]+)$ search.php?query=$1 [L]

Any help will be much apprecited

2

Answers


  1. Your current .htaccess rules are almost there, but you need to tweak them slightly to achieve the desired behavior.

    here is a suggestion:

    RewriteEngine On
    
    # Match URLs without query parameters
    RewriteRule ^search/?$ search.php [L]
    
    # Match URLs with query parameters
    RewriteRule ^search/([^/]+)/?$ search.php?title=$1 [L,QSA]
    

    the QSA flag at the end means "query string append", which ensures that existing query parameters are preserved when adding title=loremipsum.

    Login or Signup to reply.
  2. RewriteEngine On
    RewriteRule ^search/([^/]+)$ /search.php?query=$1 [L]
    RewriteCond %{THE_REQUEST} s/search.php?query=([^&s]+)s [NC]
    RewriteRule ^ /search/%1? [R=301,L]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search