简单的URL重写失败
我有一个非常简单的目标:重写我的PHP应用程序的URL,使得localhost/slim_demo/archive
被系统解释为localhost/slim_demo/index.php/archive
,但用户看到前者。 编辑:该系统表现得好像没有重写正在发生。后一版本的URL返回数据,但前者会抛出未找到错误。简单的URL重写失败
我用下面的.htaccess
文件,但它不会发生(顺便说一下,作为第二行说,在取消它拒绝所有的请求,这表明.htaccess
是活蹦乱跳):
Options +FollowSymLinks -MultiViews -Indexes
#deny from 127.0.0.1 #Uncomment to prove that .htacess is working
RewriteEngine On
RewriteRule ^slim_demo/(.*)$ slim_demo/index.php/$1 [NC,L]
而且下面是从我apache2.conf
相关部分:
<Directory />
Options FollowSymLinks
AllowOverride None
Require all denied
</Directory>
<Directory /usr/share>
AllowOverride None
Require all granted
</Directory>
<Directory /media/common/htdocs>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
我也没有a2enmod rewrite
和service apache2 restart
。沮丧,我也添加到了我的网站可用,做了重新启动:
<Directory /media/common/htdocs/>
Options +FollowSymLinks -Indexes
AllowOverride All
</Directory>
不知道还有什么我需要做的!
因此,如果这个.htaccess文件是在slim_demo目录,您RewriteRule永远不匹配:
在目录和htaccess的背景下,格局将初步 匹配对文件系统路径,去掉前缀后 将服务器引导至当前的RewriteRule
(该模式在您的情况下是^slim_demo/(.*)$
部分)。
这意味着当您尝试获取URL localhost/slim_demo/archive
时slim_demo
部分被删除,并且您的规则永远无法匹配。
因此,你需要:
RewriteRule ^(.*)$ index.php/$1
但是这会给你带来无限循环和一个500错误。只有在REQUEST_URI没有index.php时,您才必须触发此规则。
所有在一起就变成了:
RewriteEngine On
RewriteCond %{REQUEST_URI} ^(?!/slim_demo/index\.php).*$
RewriteRule ^(.*)$ index.php/$1 [NC,L,QSA]
它的工作原理!除了我还不明白如何。让我读一读评论中的一些小问题? :) – dotslash
我很抱歉,为什么'RewriteRule ^(。*)$ index.php/$ 1'会导致无限循环?是否因为规则说“将所有内容重定向到index.php之后”,这意味着将“index.php/page_requested”重定向到index.php等等? – dotslash
@dotslash要了解这一点,最好在[关于标志L的Apache文档]中解释(https://httpd.apache.org/docs/2.2/en/rewrite/flags.html#flag_l)。当您更改URL时,Apache的工作将再次以新的URL开始,并且如果再次遇到.htaccess,它将再次运行。然后你会有一个无限循环:/ slim_demo/archive => /slim_demo/index.php/archive=> /slim_demo/index.php/index.php/archive => etc ...如果你使用的是Apache v2.4 ,有一个新的标志'END'来处理这种问题:https://httpd.apache.org/docs/2.4/en/rewrite/flags。html#flag_end – Zimmi
哪里是你的.htaccess在什么位置? – Zimmi
你的“slim_demo”目录中是否有htaccess文件? –
@Zimmi @Jon是的,它在'slim_demo'目录中! – dotslash