HTACCESS complicated query
Hey! I have this question about HTACCESS.
I know how to do a 301 from all lowercase to all uppercase and vice versa but I'm confused with this one.
开发者_开发技巧I want to do a 301 redirect via HTaccess. The pages I have look like www.mysite.com/James or www.mysite.com/Paul
I want pages like www.mysite.com/JAMES or www.mysite.com/james or www.mysite.com/jAmES to 301 redirect to www.mysite.com/James (proper case).. any idea how to do this please?
I think you just want something like this, although as Pekka mentioned it's a bit difficult to know for sure without more detail:
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/[A-Z][a-z]+$
RewriteRule ^/?([A-Za-z])([A-Za-z]+)$ http://www.example.com/${toupper:$1}${tolower:$2} [L,R]
Keep in mind that you have to actually have the toupper
and tolower
maps defined in your server's configuration, which is not possible if you don't have control over the server or your virtual host definition.
httpd.conf
or a virtual host:
RewriteMap toupper int:toupper
RewriteMap tolower int:tolower
As a side note, I'm fairly confused why mod_rewrite
's internal map functions have to be explicitly declared, but that's what the code says (and what the documentation fails to mention), so there you go.
Edit: To capitalize one or more words in a space-delimited string, we can do this:
RewriteEngine On
RewriteCond $1 (.*)((?:\s|\A)[A-Za-z])([A-Za-z]+)$
RewriteCond $1 !^(\s?[A-Z][a-z]+)+$
RewriteRule /?(.*) %1 [N,E=CC_URL:${toupper:%2}${tolower:%3}%{ENV:CC_URL}]
RewriteCond %{ENV:CC_URL} !=""
RewriteRule .* http://www.example.com/$0%{ENV:CC_URL} [L,R]
I'd thoroughly test this one out before letting it run in the wild though. I'm fairly certain it should work fine, but since there's the possibility that it could cause an infinite loop and send one of your httpd
children spiraling out of control...use with caution.
Edit: Whoops, I realized that the second condition wouldn't work if there was part of the URL that was actually formatted correctly. I've changed it to be more reliable now.
精彩评论