【问题标题】:.htaccess rewrite cond and rule cannot firgure out extra slash at end.htaccess rewritecond 和 rule 无法在末尾找出多余的斜线
【发布时间】:2013-07-25 01:29:23
【问题描述】:

我一直在谷歌搜索堆栈溢出以试图解决这个问题,但无论我尝试什么都没有快乐并且不断收到错误。

我目前正在使用此代码重写地址以删除扩展名,我前段时间从简单网站的 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 作为背景文件,因此是第二个块)

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

我已经设法让我的测试站点使用另一个 SO 帖子中的代码加载 www.website.com/page/,但只有当我输入该 url 时,如果我转到 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=0 到 page/var=0 没有图像、js 和 css 停止。当然,如果它都可以用斜线,那就更好了。

谢谢

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

【问题讨论】:

  • 如果您使用 QSA 标志,则查询字符串不会出现问题,例如 [QSA,L] 或 [R=301,QSA,L] 等。QSA 会将查询字符串附加到下一个 URL,以便保留?var=0 如果您不喜欢结尾的反斜杠,那么您最好将其从 /$1/ 删除到 /$1 并将 ? 添加到 /?$
  • 嘿,谢谢你的帮助。我确实想要结尾的反斜杠,但它不能正常工作。我快到了,我可以从外部重定向到/page/,但内部不能指向该文件!我正在使用RewriteCond %{REQUEST_FILENAME}.html -f换行RewriteRule ^/ %{REQUEST_URI}.html [L]

标签: apache .htaccess mod-rewrite url-rewriting


【解决方案1】:

这个似乎对我来说很好用,试试看:

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]

【讨论】:

  • 如果我删除 rewrite base 并输入 www..../page - 并且如果我输入 www..../page/ 并且在没有相关图像 css 等的情况下加载 - 但如果我会给出错误我添加了一个变量/page.html?var=a。我刚刚发现,如果我想要标准页面上没有变量的斜杠,我需要更新所有链接和附加文件,并在前面加上 ../ 编辑:我能问一下 ([^/]*) 做什么
  • 好的,差不多了,除了在页面和变量之间添加斜线之外,代码适用于所有内容!例子:page.html?var=a变成page?var=a,能不能改成page/?var=a 非常感谢你的帮助
  • @slappy-x 在你的第一条规则上,使用 %1/ 它会附加 ?如果有的话。
猜你喜欢
  • 1970-01-01
  • 2016-12-22
  • 2021-11-06
  • 1970-01-01
  • 1970-01-01
  • 2014-07-29
  • 1970-01-01
  • 1970-01-01
  • 2020-04-03
相关资源
最近更新 更多