Php 2.不同的访问规则
我正在尝试为我的网站设置两个不同的Php 2.不同的访问规则,php,.htaccess,Php,.htaccess,我正在尝试为我的网站设置两个不同的.htaccess规则,但仍然找不到正确的解决方案 我想在website.com/几乎所有内容上发送所有内容-这对我很有用。此外,我还想添加这条路线:website.com/car/car\u id——麻烦来了,我不知道如何设置它 以下是我的尝试: RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$
.htaccess
规则,但仍然找不到正确的解决方案
我想在website.com/几乎所有内容上发送所有内容-这对我很有用。此外,我还想添加这条路线:website.com/car/car\u 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
你能帮我修改第二条规则吗?从上到下逐行重写作品
检查初始条件(文件不存在)后,它将遇到您的第一条规则
它说,如果URL是什么,修改它。它还有两个选择:
- “QSA”表示追加查询字符串
- “L”表示这是最后一条规则,请停止处理
由于这个“L”,它停止了处理,并且在这个规则之后不会发生任何事情
要解决此问题,请执行以下操作:
- 更改规则的顺序,因为“car/”更具体
- 还将L和QSA标志添加到“car/”规则中
因此:
更好的解决方案是,将所有请求重定向到index.php
,然后解析$\u服务器['request\u URI']
。然后,您需要为每一个新的未来更改htaccess
在apache中,您可以这样做>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php [L]
在php中,您可以手动填充$\u 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
更好的做法是创建一个类,该类将处理URL。而不是
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]
另外,我用空行分隔了我的规则,所以很清楚有多少。上面显示了3条不同的规则。请注意,L
标志告诉它,如果应用了该规则,将停止进一步处理重写规则。感谢您的帮助Dutow,我在尝试此操作时遇到了一些问题。首先,所有CSS+图像在网站上都不起作用,然后,在主页上显示不正确的页面,汽车页面(car.php
文件)也显示不正确的页面。CSS和图像不起作用,因为对于html来说,你现在在一个文件夹(/car/)中,所以你必须确保指向资源的链接是绝对的。例如
,而不是
。css的背景也是如此:url(path/to/images.jpg)
声明必须是/path/to/images/jpg
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]