Search code examples
.htaccessgethttp-status-code-404trailing-slash

Add trailing slash to url only if parameter is correct


I use the configuration below in .htaccess file to force trailing slash at the end of the url. But this setting is not good when an url is wrong (city parameter is not present in the database) because it redirect /wrongcity to /wrongcity/ instead to send a 404 error. How can I solve this problem?

RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f

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

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

Solution

  • It shouldn't matter that it's redirecting. When your index.php script sees the "wrongcity", it should return a 404.

    The htaccess file has no idea what's a valid city or a wrong city, it blindly routes everything to index.php, so it's up to your php script to return the 404.

    You can alternatively remove the redirect from your .htaccess file and have your php script redirect for you. If it sees a missing trailing slash, it checks if the city is valid or not, if not, return 404, if valid, redirect to include trailing slash.

    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();    
    }