尾随斜线问题 [英] Trailing slashes problem
问题描述
当我输入http://example.com/Hello%20There/"时,它显示索引页面是:http://example.com/Hello%20There/index.html" .
When I type this "http://example.com/Hello%20There/" , it displays the index page wich is : "http://example.com/Hello%20There/index.html" .
好吧,我想做的是当用户输入http://example.com/Hello%20那里"(所以就像第一个一样,只是它没有尾部斜杠).
Well, what I want to do is when the user types "http://example.com/Hello%20There" (so like the first one except it doesn't have a trailing slash).
我尝试了很多东西,特别是正则表达式,但没有任何效果,因为我认为服务器在找到空格(URL 中的%20")时停止 reg exp 进程.
I tried many things and specially regular expressions, but nothing works because I think that the server stops the reg exp process when he finds a space ("%20" in the URL).
我试过这个正则表达式:
I tried this reg exp:
Options +FollowSymLinks
rewriteEngine On rewriteCond %{REQUEST_URI} ^(.*)\ (.*html)$
rewriteRule ^.*$ %1-%2 [E=space_replacer:%1-%2]
rewriteCond %{ENV:space_replacer}!^$
rewriteCond %{ENV:space_replacer}!^.*\ .*$
rewriteRule ^.*$ %{ENV:space_replacer} [R=301,L]
并加上:
DirectorySlash On
在 Apache 的mod_dir"模块中.
in the "mod_dir" module of Apache.
所以,我的问题是:- 当用户输入 url 时如何告诉服务器添加尾部斜杠没有尾部斜杠;$
So, my question is: - How to tell to the server to add a trailing slash when the user types an url without a trailing slash;$
推荐答案
您可以通过在字符后面附加 ?
量词来使字符可选,如下所示:
You can make a character optional by appending the ?
quantifier to it like this:
RewriteRule ^([^/]+)/?$ $1/index.html
现在 /foobar
和 /foobar/
都将被重写为 /foobar/index.html
.
Now both /foobar
and /foobar/
would be rewritten to /foobar/index.html
.
但是如果您只使用一种拼写(带或不带斜杠)并重定向另一种拼写会更好:
But it would be better if you use just one spelling, with or without the trailing slash, and redirect the other one:
# remove trailing slash
RewriteRule (.+)/$ /$1 [L,R=301]
# add trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .*[^/]$ /$1/ [L,R=301]
这些规则删除或添加缺少的尾部斜杠并执行永久重定向.
These rules either remove or add a missing trailing slash and do a permanent redirect.
这篇关于尾随斜线问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!