简体   繁体   中英

Prevent rules conflicts with htaccess' RewriteRule

I would like to use some RewriteRule s 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 :

  • each of these 2 rules work alone

  • when I use the second rule, then http://example.com/someone/blah => index.php?id=blah&user=someone works, but it seems that the root folder is no more / but /someone/ and then the CSS are not found... How to prevent the base folder to be changed in this case ?

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/">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM