htaccess url重写:添加尾部斜杠不起作用

时间:2016-07-27 09:15:10

标签: apache .htaccess redirect mod-rewrite url-rewriting

不幸的是我遇到了问题,我遇到了问题。

我会在每个URL后面添加一个尾部斜杠,然后通过301将没有斜杠的版本重定向到带有斜杠的变体。

以前,我已经成功移除了网址重写的html文件扩展名并强制执行SSL。

所以,我尝试使用以下代码添加斜杠。

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*[^/])$ /$1/ [L,R=301]

我在这个帖子上找到了这个解决方案:Htaccess: add/remove trailing slash from URL

遗憾的是,它无效。

有趣的是,例如,当我访问以下网址(末尾有斜线)时:

example.com/imprint /

我收到以下消息:此服务器上找不到请求的网址 /imprint.html /

imprint.html ???

这是我完整的.htaccess文件:

RewriteEngine On

#Activate and force ssl and redirect from non-www to www#
RewriteCond %{HTTP_HOST} ^example\.com$ [NC,OR]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]

#Removes HTMl-Extension and make URLs clean# 

#example.com/page will display the contents of example.com/page.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.+)$ $1.html [L,QSA]

#301 from example.com/page.html to example.com/page
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*\.html\ HTTP/
RewriteRule ^(.*)\.html$ /$1 [R=301,L]

#Redirect Index Files e.g. /index or /index.html
RewriteRule ^index\.html$ / [R=301,L]
RewriteRule ^(.*)/index\.html$ /$1/ [R=301,L]

#Adds a trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*[^/])$ /$1/ [L,R=301]

我希望,你可以帮助我。 : - )

1 个答案:

答案 0 :(得分:0)

当您检查!-f(不是文件)时,它也会跳过.html个文件。您可以使用[OR]

RewriteEngine On

#Activate and force ssl and redirect from non-www to www#
RewriteCond %{HTTP_HOST} ^example\.com$ [NC,OR]
RewriteCond %{HTTPS} off
RewriteRule ^(.*?)/?$ https://www.example.com/$1/ [L,R=301]

#301 from example.com/page.html to example.com/page
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*\.html\ HTTP/
RewriteRule ^(.+)\.html/?$ /$1/ [R=301,L]

#Redirect Index Files e.g. /index or /index.html
RewriteRule ^index\.html/?$ / [R=301,L]

RewriteRule ^(.+)/index\.html/?$ /$1/ [R=301,L,NE,NE]

#Adds a trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*[^/])$ /$1/ [L,R=301,NE]

#Removes HTMl-Extension and make URLs clean# 

#example.com/page will display the contents of example.com/page.html
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.+?)/?$ $1.html [L]