.htaccess 仅当参数正确时,才将尾部斜杠添加到url

.htaccess 仅当参数正确时,才将尾部斜杠添加到url,.htaccess,get,http-status-code-404,trailing-slash,.htaccess,Get,Http Status Code 404,Trailing Slash,我在.htaccess文件中使用下面的配置来强制在url的末尾添加尾随斜杠。 但当url错误时(数据库中不存在city参数),此设置不好,因为它将/ErrorCity重定向到/ErrorCity/以发送404错误。 我怎样才能解决这个问题 RewriteEngine on RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)([^/])$ /$1$2/ [L,R=301] RewriteRule ^([A-Z

我在
.htaccess
文件中使用下面的配置来强制在url的末尾添加尾随斜杠。 但当url错误时(数据库中不存在city参数),此设置不好,因为它将
/ErrorCity
重定向到
/ErrorCity/
以发送404错误。 我怎样才能解决这个问题

RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.*)([^/])$ /$1$2/ [L,R=301]

RewriteRule ^([A-Za-z0-9-]+)//?$ index.php?city=$1 [L]

它重定向不重要。当您的
index.php
脚本看到“错误城市”时,它应该返回404

htaccess文件不知道什么是有效的城市,什么是错误的城市,它会盲目地将所有内容路由到
index.php
,因此由php脚本返回404

您也可以从
.htaccess
文件中删除重定向,并让php脚本为您重定向。如果发现缺少尾随斜杠,它将检查城市是否有效,如果无效,则返回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();    
}

我认为,特别是对于SEO,错误的URL必须发送404状态,而不是301状态。