Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
957 views
in Technique[技术] by (71.8m points)

apache - Trailing slashes problem

When I type this "http://example.com/Hello%20There/" , it displays the index page wich is : "http://example.com/Hello%20There/index.html" .

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).

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] 

and also put:

DirectorySlash On 

in the "mod_dir" module of Apache.

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;$

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can make a character optional by appending the ? quantifier to it like this:

RewriteRule ^([^/]+)/?$ $1/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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...