【问题标题】:mod_rewrite redirects with absolute path in URLmod_rewrite 在 URL 中使用绝对路径重定向
【发布时间】:2019-03-28 15:49:32
【问题描述】:

我正在尝试使用 Apache mod_rewrite。我做的第一件事是将我的 url 重写为一个工作正常的 index.php 文件。但我认为我也应该删除尾部斜杠,因为我希望由 Apache 而不是我的 PHP 路由器来处理它。

这是我的.htaccess 文件的全部内容:

RewriteEngine on

# one of the attempts to remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.*)/+$
RewriteRule ^(.*)/+$ $1 [R=301,L]

# This is the rewriting to my index.php (working)
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?/$1 [L]


问题:
我阅读了几个关于删除斜杠的问题,但我找不到适合我的答案:
对于我尝试的每个答案,我都能够在没有斜杠的情况下访问我的 PHP 路由器 index.php(位于 Phunder\public\):
// Requested URL                                | No redirection
http://localhost/projects/Phunder/public/home   | http://localhost/projects/Phunder/public/home

但是当请求带有斜杠的同一页面时,我会使用包含的绝对路径重定向:

// Requested URL                                | Wrong redirection
http://localhost/projects/Phunder/public/home/  | http://localhost/C:/xampp/htdocs/projects/Phunder/public/home


其他信息:
  • 我总是在测试时清除缓存
  • 将我的上一个 RewriteRule 更改为 RewriteRule ^(.*)/?$ index.php?/$1 [L] 会导致 404 错误,其中 URL 带有尾部斜杠。
  • 实际的错误重定向会导致 403 错误

我是 mod_rewrite 的初学者,我并不总是理解我尝试的内容(很遗憾)。有什么我错过或滥用的吗?我应该怎么做才能获得预期的行为?

【问题讨论】:

    标签: regex apache .htaccess mod-rewrite pcre


    【解决方案1】:

    重定向规则需要绝对 URL 或 RewriteBase。您可以像这样从%{REQUEST_URI} 提取完整的 URI:

    RewriteEngine on
    
    # one of the attempts to remove trailing slash
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} ^(.+)/+$
    RewriteRule ^ %1 [R=301,NE,L]
    
    # This is the rewriting to my index.php (working)
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php?/$1 [L,QSA]
    

    【讨论】:

    • 它有效,谢谢!但我并不完全理解 RewriteRule。我知道%1 指的是我们在上一行中获得的捕获组,但^ %1 是什么意思?我会自己研究以了解NE 标志。
    • ^ 是一个正则表达式,带有始终匹配的刚刚开始的锚点。 %1 是在 RewriteCond 中捕获的值的反向引用。 NE 标志用于重定向后 URI 的不转义。
    • 哦,对了,太好了。非常感谢,我现在完全理解了
    猜你喜欢
    • 1970-01-01
    • 2020-09-26
    • 2021-10-06
    • 2012-02-24
    • 2014-01-07
    • 1970-01-01
    • 2021-04-05
    • 2021-11-10
    • 2012-01-27
    相关资源
    最近更新 更多