仅当参数正确时才将尾部斜杠添加到 url
Add trailing slash to url only if parameter is correct
我在 .htaccess
文件中使用下面的配置来强制在 url 末尾添加斜线。
但是当 url 错误时(城市参数不在数据库中),此设置并不好,因为它将 /wrongcity
重定向到 /wrongcity/
而不是发送 404 错误。
我该如何解决这个问题?
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)([^/])$ // [L,R=301]
RewriteRule ^([A-Za-z0-9-]+)//?$ index.php?city= [L]
重定向应该无关紧要。当您的 index.php
脚本看到 "wrongcity" 时,它应该 return 一个 404。
htaccess 文件不知道什么是有效城市或错误城市,它盲目地将所有内容路由到 index.php
,所以这取决于您的 php 脚本到 return 404 .
您也可以从 .htaccess
文件中删除重定向,让 php 脚本为您重定向。如果发现缺少尾部斜杠,它会检查城市是否有效,如果无效,return 404,如果有效,重定向以包含尾部斜杠。
if ($city_exist)
{
$url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if ( substr($url, -1) != "/" )
header("Location: ".$this_url."/"); //redirect to force trailing slash
}
else
{
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
exit();
}
我在 .htaccess
文件中使用下面的配置来强制在 url 末尾添加斜线。
但是当 url 错误时(城市参数不在数据库中),此设置并不好,因为它将 /wrongcity
重定向到 /wrongcity/
而不是发送 404 错误。
我该如何解决这个问题?
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)([^/])$ // [L,R=301]
RewriteRule ^([A-Za-z0-9-]+)//?$ index.php?city= [L]
重定向应该无关紧要。当您的 index.php
脚本看到 "wrongcity" 时,它应该 return 一个 404。
htaccess 文件不知道什么是有效城市或错误城市,它盲目地将所有内容路由到 index.php
,所以这取决于您的 php 脚本到 return 404 .
您也可以从 .htaccess
文件中删除重定向,让 php 脚本为您重定向。如果发现缺少尾部斜杠,它会检查城市是否有效,如果无效,return 404,如果有效,重定向以包含尾部斜杠。
if ($city_exist)
{
$url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if ( substr($url, -1) != "/" )
header("Location: ".$this_url."/"); //redirect to force trailing slash
}
else
{
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
exit();
}