为什么Apache在使用RewriteRule并转到末尾带有斜杠的URL时抛出禁止的错误?
我想为我的应用程序构建一个搜索页面,我正在使用为什么Apache在使用RewriteRule并转到末尾带有斜杠的URL时抛出禁止的错误?,apache,.htaccess,trailing-slash,Apache,.htaccess,Trailing Slash,我想为我的应用程序构建一个搜索页面,我正在使用.htaccess使URL看起来更好。搜索页面位于localhost/search。此外,可以在URL末尾附加两个可选参数,如下所示:localhost/search/post/12345。但是,当没有附加任何参数时,只有一个尾随斜杠(localhost/search/),Apache会抛出一个禁止的错误。我不知道为什么会发生这种情况,因为服务器上没有名为search的文件夹 为了更好地说明我的问题,以下是有效链接和无效链接: 工作: localh
.htaccess
使URL看起来更好。搜索页面位于localhost/search
。此外,可以在URL末尾附加两个可选参数,如下所示:localhost/search/post/12345
。但是,当没有附加任何参数时,只有一个尾随斜杠(localhost/search/
),Apache会抛出一个禁止的错误。我不知道为什么会发生这种情况,因为服务器上没有名为search
的文件夹
为了更好地说明我的问题,以下是有效链接和无效链接:
工作:
localhost/search
localhost/search/post
localhost/search/post/
localhost/search/post/12345
localhost/search/post/12345/
localhost/search/
search.php
与.htaccess
文件一起位于根目录中。下面是.htaccess
文件:
RewriteEngine On
# Redirect HTTP traffic to HTTPS
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ $1 [R=301,L]
# Resolve .php file for extension-less php urls
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^/.]+)$ $1.php [L]
# Search parameters
RewriteRule ^search?/?([0-9a-zA-Z_-]+)?/?([0-9a-zA-Z_-]+)?/?$ search.php?type=$1&data=&2
# 404 error
ErrorDocument 404 /errors/404.php
我根据有关StackOverflow的有用答案解决了这个问题。在
.htaccess
文件中,我更改了以下行:
# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ $1 [R=301,L]
致:
# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ /$1 [L,R=301]