Basj
Basj

Reputation: 46503

Prevent rules conflicts with htaccess' RewriteRule

I would like to use some RewriteRules to transform :

Here is the htaccess :

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?id=$1 [L]
RewriteRule ^(.*)/(.*)$ /index.php?id=$2&user=$1 [L]
</IfModule>

But it seems that the two last rules are incompatible : with this htaccess, I get some 500 Internal Server Error.

How to create two rules such that they do not "overlap" each other?

Notes :

Upvotes: 0

Views: 92

Answers (1)

Prix
Prix

Reputation: 19528

You have 4 issues:

  1. your first rule (.*) will convert anything into /index.php?id=$1
  2. your second rule does not verify if a file or folder exists and might fall into a infinite loop causing a 500 internal server error.
  3. the order of your rules
  4. you're using relative paths to serve CSS and Images which causes it to fail with your URL formats, such as domain.com/anything/anything

To fix the redirect issue, you can use this:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    RewriteRule ^index\.php$ - [L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^/]+)/([^/]+)$ /index.php?id=$2&user=$1 [L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^/]+)$ /index.php?id=$1 [L]
</IfModule>

Since I've changed the regex (to ([^/]+) which means anything not a /) that catches the data you want and the order won't matter in this scenario as it will specifically match:

domain.com/anything

And

domain.com/anything/anything

To fix the CSS and Images you can use the base TAG to define your absolute URL into your HTML:

<base href="http://domain.com/">

Upvotes: 2

Related Questions