Reputation: 48453
I am trying to set up for my website two different .htaccess
rules, but I still cannot find the correct solution.
I would like to route everything on website.com/almost-everything
- this is working me well. And further, I would like to add yet this route: website.com/car/car_id
- and here comes troubles, I don't know how to set up it.
Here are my attempts:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?skill=$1 [L,QSA]
RewriteRule ^car/(.*)$ ./index.php?id=car&car_id=$1 # the wrong rule - the page with website.com/car/car_id just doesn't display the correct file
Could you help me please with the second rule?
Upvotes: 0
Views: 78
Reputation: 10537
Instead of
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?skill=$1 [L,QSA]
RewriteRule ^car/(.*)$ ./index.php?id=car&car_id=$1 # the wrong rule - the page with website.com/car/car_id just doesn't display the correct file
I would do this
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.+) - [PT,L] ## passthru + last rule because the file or directory exists. And stop all other rewrites. This will also help your css and images work properly.
RewriteRule ^car/(.*)$ /index\.php?id=car&car_id=$1 [L,QSA]
RewriteRule ^(.*)$ /index\.php?skill=$1 [L,QSA]
P.s. I seperated my rules with blank lines so it is clear how many there are. The above shows 3 distinct rules.
Upvotes: 1
Reputation: 43552
A better solution would be, to redirect all your request to index.php
, and then parse $_SERVER['REQUEST_URI']
. Then you newer need to change htaccess for every new future.
In apache you can do that like this >
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php [L]
In php you can manualy fill your $_GET
, so it would look like your old requests...
$f = explode('/', substr($_SERVER['REQUEST_URI'], 1));
switch ($f[0]) {
case 'car' :
$_GET['id'] = $f[0];
$_GET['car_id'] = $f[1];
break;
default:
$_GET['skill'] = $f[0];
}
# your old code, that reads info from $_GET
A better practice it would be to make class, that will take care of the urls.
Upvotes: 0
Reputation: 5668
Rewrite works line by line, from the top to the bottom.
After checking the initial conditions (file doesn't exists), it encounters your first rule.
It says, if the URL is anything, modify it. It also has two options:
Because of this "L", it stops the processing, and nothing happens after this rule.
To fix this:
So:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^car/(.*)$ ./index.php?id=car&car_id=$1 [L,QSA]
RewriteRule ^(.*)$ index.php?skill=$1 [L,QSA]
Upvotes: 1