.htaccess 如果url包含关键字,则添加尾部斜杠

.htaccess 如果url包含关键字,则添加尾部斜杠,.htaccess,mod-rewrite,.htaccess,Mod Rewrite,我已经尝试了几个版本的尾随斜杠代码,但没有一个适合我。我只想在url包含关键字新闻时添加尾随斜杠,所以 domain.com/news domain.com/news/category/foo domain.com/news/archive/august-2018 应该触发它来添加斜杠。我现在有这个 RewriteCond %{REQUEST_URI} ^/(news.*)$ RewriteRule ^/news(.*[^/])$ %{REQUEST_URI}/ [R=301,L] 您可以使

我已经尝试了几个版本的尾随斜杠代码,但没有一个适合我。我只想在url包含关键字新闻时添加尾随斜杠,所以

domain.com/news
domain.com/news/category/foo
domain.com/news/archive/august-2018
应该触发它来添加斜杠。我现在有这个

RewriteCond %{REQUEST_URI} ^/(news.*)$
RewriteRule ^/news(.*[^/])$ %{REQUEST_URI}/ [R=301,L]

您可以使用两个单独的规则来执行此操作,一个单独用于
新闻
,另一个单独用于
新闻/categroy/foo

# direct news to news/
RewriteRule ^news$ news/ [L,R=301]

# if no trailing slash, direct news/* to news/*/
RewriteCond %{REQUEST_URI} ^(.*[^/])$
RewriteRule ^news/(.*)$ news/$1/ [L,R=301]
这三条规则导致:

http://www.example.com/news => http://www.example.com/news/
http://www.example.com/news/category/foo => http://www.example.com/news/category/foo/
http://www.example.com/news/archive/august-2018 => http://www.example.com/news/archive/august-2018/
您可以使用测试这些规则。

尝试使用以下规则

RewriteRule ^news$ http://%{HTTP_HOST}%{REQUEST_URI}/ [R=301]

道歉!我已经更新了上面的答案,以检查是否有一个已经尾随的斜杠:)@VeeK是否按预期工作?如果有,请接受我的回答以帮助他人:)我认为这很好,但我在localhost上遇到了一个问题。也许你能帮忙<代码>http://localhost/CCR/Website/news/cat/latest-news转到
http://localhost/E:/Documents/Projects/CCR/Website/news/cat/latest-新闻/
。我不知道为什么要添加文件路径。我会将其上载到域中进行测试,并让您知道结果。它不起作用。请不要用斜线结束。它将路径添加到url。