skip to Main Content

Here are some example urls I wish to rewrite:

https://website.com?c=food&s=cheese&p=3
https://website.com?c=food&s=cheese
https://website.com?s=cheese

I wish for the above to be rewritten to:

https://website.com/food/cheese/3
https://website.com/food/cheese
https://website.com/cheese

Here is my htaccess file:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^.*.(jpg|css|js|gif|png)$ [NC]
RewriteRule ^([^/]*)/([^/]*)/([^/]*)$ /?c=$1&s=$2&p=$3 [L]
RewriteRule ^([^/]*)/([^/]*)$ /?c=$1&s=$2 [L]
RewriteRule ^([^/]*)$ /?s=$1 [L]

Can anyone see whats going wrong? I a remove the last line

RewriteRule ^([^/]*)$ /?s=$1 [L]

The page loads however, it seems to be rewriting the css and js files?

2

Answers


  1. A RewriteCond is only applicable to the immediate next RewriteRule. Since you have multiple rules needing same conditions, it is better to define a separate rule to exclude all files, directories and known URIs.

    RewriteEngine On
    
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d [OR]
    RewriteCond %{REQUEST_URI} .(jpg|css|js|gif|png)$ [NC]
    RewriteRule ^ - [L]
    
    RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?$ ?c=$1&s=$2&p=$3 [L,QSA]
    
    RewriteRule ^([^/]+)/([^/]+)/?$ ?c=$1&s=$2 [L,QSA]
    
    RewriteRule ^([^/]+)/?$ ?s=$1 [L,QSA]
    
    Login or Signup to reply.
  2. The reason it will be failing/causing a server error is because it is placed in infinite recursion – ^([^/]*)$ redirects to /?s=$1 which is picked up again by ^([^/]*)$, repeat ad infinitum.

    Try this instead. It’s not necessarily the best rewrite rule but it should fix your specific problem:

    RewriteRule ^([^/]*)$ index.php?s=$1 [L,QSA]

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search