apache - .htaccess rewritecond 和规则无法找出末尾的额外斜杠

标签 apache .htaccess mod-rewrite url-rewriting

我一直在谷歌上搜索堆栈溢出,试图找出这个问题,但没有任何乐趣,并且无论我尝试什么,都会不断出现错误。

我目前正在使用此代码重写地址以删除扩展名,我不久前从 SO 帖子中获得了它,用于简单的网站:

RewriteEngine on

# To externally redirect /dir/foo.html to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.html [NC]
RewriteRule ^ %1 [R=301,L]

# To internally forward /dir/foo to /dir/foo.html
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [L]

# To externally redirect /dir/foo.html to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.phtml [NC]
RewriteRule ^ %1 [R=301,L]

# To internally forward /dir/foo to /dir/foo.html
RewriteCond %{REQUEST_FILENAME}.phtml -f
RewriteRule ^ %{REQUEST_URI}.phtml [L]

(我使用 phtml 文件作为 ui 文件,使用 php 作为后台文件,因此是第二个 block )

这对我来说效果很好,但现在我在一个网站上,我想将 get 变量提供给页面以进行书签等,并且不希望地址类似于 www.website.com/page ?var=0

我已经设法让我的测试网站使用另一个SO帖子中的代码加载www.website.com/page/,但只有当我输入该网址时,如果我去它就不会重写到 page.html 并且不会加载附加文件 css、js (我理解这是因为文件有相对路径) 编辑: 我现在明白这与 -f || 有关。 !-F; 代码:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^([^/]+)/$ $1.html
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.html

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]

我可以接受是否有尾随斜杠,但我确实想在存在变量时添加它,例如 page?var=0page/var=0 没有图像、js 和 css 停止。当然,如果都可以用斜杠那就更好了。

谢谢

编辑:当网站和 .htaccess 位于子文件夹中时也需要工作,例如:mysite.com/example/websitedemonstration/page

最佳答案

这个似乎对我来说效果很好,试一试:

Options +FollowSymLinks -MultiViews

RewriteEngine On
RewriteBase /

# To externally redirect /dir/foo.html to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.(html|phtml) [NC]
RewriteRule ^ %1 [R=301,L]

# To internally forward /dir/foo to /dir/foo.html
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^([^/]*)/?$ $1.html [L]

# To internally forward /dir/foo to /dir/foo.phtml
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.phtml -f
RewriteRule ^([^/]*)/?$ $1.phtml [L]

关于apache - .htaccess rewritecond 和规则无法找出末尾的额外斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17839693/

相关文章:

php - 如果使用方法 GET,如何加密 URL 参数

apache - 重写到新域?用url查询?不工作。 :( help

php - Prestashop Webservice api url 重定向

apache - .htaccess 上的 mod_rewrite 将主文件夹映射到子文件夹

linux - 如何将用户 www-data 写入权限分配给用户文件夹,而不分配用户给其他用户文件夹?

.htaccess - htaccess 内部服务器错误

php - 将 .htaccess 应用于所有子目录

c++ - 如何在 MS visual studio 调试器中查看 DOMString(来自 apache xerces 库)?

javascript - 如何在网站链接前添加文本,fx store.mywebsite.com

.htaccess - 使用 .htaccess 更改显示的 URL,但不实际重定向内容?