简体   繁体   English

Mod重写和404重定向

[英]Mod Rewrite and 404 redirect

I want make websitename.com/file.php become websitename.com/file/ and after browsing thru StackOverflow, with countless try and error, this is what I got and it is working. 我希望使websitename.com/file.php成为websitename.com/file/,并在通过StackOverflow浏览后,进行无数次尝试和错误操作,这是我所得到的,并且正在运行。

RewriteEngine on
RewriteRule ^(.*)\/$ $1.php [NC]

I also added this to header.php so that if any filename shows up with the .php extension, it will redirect to the 'slashed' URL I wanted. 我还将此文件添加到header.php,以便如果显示任何文件名并带有.php扩展名,它将重定向到我想要的“斜线” URL。

$NoPhpUrl = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
$NoPhpUrl = $NoPhpUrl .'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if(strstr($NoPhpUrl , ".php"))
{
    $NoPhpUrl = str_replace(".php","/", $NoPhpUrl );
    header("Location: ".$NoPhpUrl );
}

The issue I have currently is when I type this link websitename.com/file (without slash at the end), it will go to a 404 page. 我当前遇到的问题是,当我输入此链接websitename.com/file (末尾没有斜杠)时,它将转到404页。

I'm ok with the 404 page if the file does not exist in the directory. 如果目录中不存在该文件,则可以使用404页面。 But if it does, is there a way to force the slash to appear at the end of the url (if file exist) without making it go to 404? 但是,如果可以,是否有一种方法可以强制将斜杠显示在url的末尾(如果文件存在)而不使它进入404?

You should try your rules this way and also turn off multiviews. 您应该以这种方式尝试规则,并关闭多视图。 I added force trailing slash as I would do it in Apache instead of PHP. 我添加了强制尾部斜杠,就像在Apache而不是PHP中那样。 Server side should be preferred versus code redirects. 服务器端应该比代码重定向更可取。

Options -MultiViews
RewriteEngine on

#force trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$ [NC]
RewriteRule ^(.*)$ /$1/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.+)/$ $1.php [L,NC]

check in your if condition, you're replacing .php with /. 检查您的if条件,是否用/替换.php。 so, this is the reason why you can't access in path without /. 因此,这就是为什么没有/不能在路径中访问的原因。 check out. 查看。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM