0

我正在尝试为我的网站设置两个不同的.htaccess规则,但我仍然找不到正确的解决方案。

我想把所有东西都安排website.com/almost-everything好——这对我很有效。此外,我还想添加这条路线:website.com/car/car_id- 麻烦来了,我不知道如何设置它。

这是我的尝试:

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

你能帮我解决第二条规则吗?

4

3 回答 3

1

逐行重写作品,从上到下。

检查初始条件(文件不存在)后,它会遇到您的第一条规则。

它说,如果 URL 是任何东西,请修改它。它还有两个选项:

  • “QSA”表示追加查询字符串
  • “L”表示这是最后一条规则,所以停止处理

由于这个“L”,它停止了处理,并且在这条规则之后没有任何反应。

要解决这个问题:

  • 更改规则的顺序,因为“car/”更具体
  • 还将 L 和 QSA 标志添加到“car/”规则中。

所以:

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]
于 2013-01-17T18:10:04.773 回答
1

代替

    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

我会这样做

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]

Ps 我用空行分隔我的规则,所以很清楚有多少。上面显示了 3 个不同的规则。

于 2013-01-17T18:43:51.420 回答
0

更好的解决方案是将所有请求重定向到index.php,然后解析$_SERVER['REQUEST_URI']. 然后,您需要为每个新的未来更改 htaccess。

在 apache 中你可以这样做 >

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php [L]

在 php 中,您可以手动填写您的$_GET,所以它看起来像您的旧请求......

$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

一个更好的做法是上课,这将照顾网址。

于 2013-01-17T18:13:53.460 回答