Extensionless URL trailing slash redirect

99封情书 提交于 2019-12-18 18:08:54

问题


I've tested the code below on several domains hosted on Dreamhost and it works—except on newer domains I've added within the last year.

RewriteEngine on

#unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ $1 [R=301,L]

#redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} ^(.*)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.*)\.php$ $1 [R=301,L]

#resolve .php file for extensionless php urls
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [L]

example that works:

ryanvanetten.com/resources/lame/ and ryanvanetten.com/resources/lame.php both redirect to ryanvanetten.com/resources/lame and the actual file that is served is lame.php

broken example:

airve.com/test/file properly serves file.php but the redirects airve.com/test/file/ and airve.com/test/file.php don't work. Try them and you'll see they seem to be spitting out the internal absolute path. The same thing occurred when I tried each of the redirects independently and when I tried the basic redirect below.

Redirect 301 /test/file/ /test/file

There is nothing else in .htaccess. Any idea on what the issue is?


回答1:


You are redirecting to $1 in both cases, and you don't have a RewriteBase directive to tell Apache where to root such a relative path.

Try adding a root slash before the $1 to anchor it to the root of your webserver, for instance:

RewriteRule ^(.*)$ /$1.php [L]


来源:https://stackoverflow.com/questions/6325314/extensionless-url-trailing-slash-redirect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!