.htaccess删除trailing / unless目录

时间:2017-03-24 00:18:01

标签: php apache .htaccess mod-rewrite

到目前为止,这是我的.htaccess:

RewriteEngine On 
RewriteBase /
RewriteCond %{SERVER_PORT} 80 
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/[0-9a-zA-Z_-]+$
RewriteRule ^(.*)$ https://example.com/$1 [R,L]

RewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [L]

Options +FollowSymLinks

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

RewriteRule ^.*$ ./index.php

## REMOVE TRAILING /
#if its not a directory
RewriteCond %{REQUEST_FILENAME} !-d
#and it has a trailing slash then redirect to URL without slash
RewriteRule ^(.+)/$ /$1 [L,R=301]

我有这样的结构:

https://example.com/page-name

作为字符串查询返回index.php,在这种情况下它将是$_SERVER['REQUEST_URI'] = 'page-name'

对于搜索引擎优化和规范的原因,我想重定向尾随/使用301重定向,如下所示:

如果他们输入:

https://example.com/page-name/

应该重定向到

https://example.com/page-name

我的当前.htaccess会重定向到https://example.com/index.php,如果他们输入尾随/我无法弄清楚如何修复它。

1 个答案:

答案 0 :(得分:1)

您必须重新排序规则,在内部规则之前保留外部重写规则(带R标志的规则),

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ /$1 [L,R]
#other rules