我正在尝试使用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]
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 ^(.*)/?$ index.php?/$1 [L]
会导致 404错误,URL带有斜杠。我是mod_rewrite的初学者,我并不总是(很难)理解我的尝试。有什么我想念或滥用的东西吗?我应该怎么做才能获得预期的行为?
答案 0 :(得分: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]