0

I have theses rules:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule materia/([^/]+)/?$ article.php?slug=$1 [QSA,NC]
  RewriteRule busca/?s=([^/]+) search.php?s=$1 [QSA,NC]
  RewriteRule ^([^/]+)/?$ index.php?slug=$1 [QSA,NC]
</IfModule>

But the second rewrite rules is not being applied when the URL is something like http://website.test/busca/?s=teste

htaccess tester: https://htaccess.madewithlove.be?share=28e2b25d-f6ef-5faa-a5c6-a412a87d5523

marcelo2605
  • 2,734
  • 4
  • 29
  • 55
  • 2
    RewriteRule matches against the _path_ component of the URL only. If you want to do anything based on the query string, you need to do that with a RewriteCond. https://stackoverflow.com/questions/13073253/how-to-redirect-urls-based-on-query-string – CBroe Jul 23 '18 at 13:00

1 Answers1

1

Several mistakes here:

  1. to match a query string (?s=xxx), you need to use a RewriteCond on %{QUERY_STRING}

  2. RewriteCond scope is for very next rule only. In your case, it only checks if it's not an existing folder/file for the first rule.

  3. Use L flag after each rule, unless you know what you're doing.

  4. Use a RewriteBase or absolute paths.

  5. QSA flag is not necessary when you rewrite manually the query string. All it does is to append the query string (before the rewrite) to the rewrite target.

All-in-one, here is how your rules should look like

RewriteEngine On

# Don't touch existing folders/files
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

RewriteRule ^materia/([^/]+)/?$ /article.php?slug=$1 [L,NC]

RewriteCond %{QUERY_STRING} ^s= [NC]
RewriteRule ^busca/?$ /search.php [L,QSA,NC]

RewriteRule ^([^/]+)/?$ /index.php?slug=$1 [L]
Justin Iurman
  • 18,954
  • 3
  • 35
  • 54
  • Thanks for the explanations @Justin Iurman. I have justa another question. I need to add a `RewriteBase /site/`. But adding this line after `RewriteEngine On` don't make any change. The rules are skipping it. – marcelo2605 Jul 23 '18 at 13:14
  • If you use a `RewriteBase` then remove leading `/`'s for each `RewriteRule` target – Justin Iurman Jul 23 '18 at 13:52