Apache mod_rewrite重定向,保留子目录名

时间:2011-07-19 16:04:48

标签: apache mod-rewrite

我想知道这是否可行。

我有一个单页网站,我想在其中加入一个带有文件名的尾部斜杠,该文件名固定在该网站上的某个部分。我试图避免使用哈希或哈希爆炸。

例如; www.example.com/recent

现在,我正在删除任何尾随斜杠,但我得到了/recent的404,因为它需要一个文件。

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

是否可以重定向到www.example.com,但仍然维护/recent而服务器认为它不是文件,所以我可以在客户端(php / js)读取它?更多以便我可以继续使用后退和前进按钮。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

TBH对我来说并不是100%清楚你想要什么。据我了解,您希望将URL www.example.com/recent重写(内部重定向,当URL在浏览器中保持不变时)到www.example.com/index.php?page=recent(或类似的东西)。

DirectorySlash Off
Options +FollowSymLinks -MultiViews

RewriteEngine On
RewriteBase /

# remove trailing slash if present
RewriteRule ^(.*)/$ /$1 [R=301,L]

# do not do anything for already existing files
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .+ - [L]

# rewrite all non-existing resources to index.php
RewriteRule ^(.+)$ /index.php?page=$1 [L,QSA]

使用上述规则(需要放在网站根文件夹中的.htaccess中),这可以实现。对www.example.com/recent的请求将被重写为www.example.com/index.php?page=recent,因此您的单页服务器端脚本知道请求了哪个URL。与任何其他不存在的资源相同,例如www.example.com/hello/pink/kitten => www.example.com/index.php?page=hello/pink/kitten

可能没有必要将最初请求的URI作为page参数传递,因为您应该能够通过$_SERVER['REQUEST_URI']通过{{1}}访问它。


如果我误解了你并且这不是你想要的,那么你必须澄清你的问题(用更多细节更新它,听起来很清楚)。