当正斜杠位于URL结尾时重定向

时间:2014-02-28 14:53:06

标签: regex apache mod-rewrite

我的.htaccess文件位于根HTML目录中,如下所示。

我也有test.php和manual.png也位于根HTML目录中,test.php就是以下内容:

<!DOCTYPE html><html><body><img src="manual.png"></body></html>

当我将http://www.myDomain.com/testit放入浏览器时,会显示页面并显示manual.png。

当我将http://www.myDomain.com/testit/放入浏览器(而不是正斜杠)时,页面仍然会被渲染,但是manual.png是一个断开的链接。

在包含尾部斜杠时,我需要更改哪些内容才能显示图像(除了在HTML中绝对使用我的所有链接)?如果不可能,如果它具有尾部斜杠,我如何阻止HTML页面首先呈现?最后,请提供正在发生的事情的解释。

谢谢

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

## If the request is for a valid directory, file, or link, don't do anything
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -l
RewriteRule ^ - [L]

# replace my-page with test.php?p=my-page
RewriteRule ^(testit)/?$ test.php?p=$1 [L,QSA]

RewriteRule ^([^.]+)$ $1.html [L]   #Replaces file if "." is not in the string (i.e. it will not replace file.html, but will replace file

</IfModule>

1 个答案:

答案 0 :(得分:1)

当浏览器访问没有尾部斜杠的URL时,它会将其视为文件。这意味着基目录将是文件的父目录。如果URL 具有尾部斜杠,则浏览器将其视为目录并使其成为基本目录。

为了防止出现此问题,Apache有一个模块可以自动为目录请求添加一个尾部斜杠。但是因为你正在使用重写,所以Apache不会添加任何内容。

您可以通过强制执行尾部斜杠或缺少斜杠来解决此问题。

# The following should remove the trailing slash.
# Add it before your my-page -> test.php?p=my-page rule
RewriteRule ^(.+)/$ $1

顺便说一句,您可以使用this site来测试重写规则