.htaccess: Redirect all requests to a subdirectory except if an exact directory exists
Any request to www.example.com/*
must be redirected to www.example.com/blog/*
If no www.
prefix, add 开发者_开发问答it.
Importantly, if there exists any directory matching the request URI, don't redirect.
Example:
(www.)example.com/<request>
-> www.example.com/blog/<request>
except <request> === <dirname>
Following the above 3 conditions, how do I code a .htaccess? Please help! Thx ;-)
This should do what you wanted. I also added in a "don't redirect if this file exists", since I wasn't sure what was in your existing directories. You can try removing it by taking out the second RewriteCond
if you don't want it, but I think it's probably necessary to some extent.
RewriteEngine On
# Check if the requested path is not a real file or a
# real directory
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
# If the current request doesn't start with "blog", and
# it's not a real file or directory based on the above
# conditions, add "blog" to the front of the request, and
# mark an environment variable that indicates we'll need
# to redirect
RewriteRule !^blog blog%{REQUEST_URI} [E=CHANGED:TRUE]
# Check if the host doesn't start with "www.", or if we've
# marked the change variable above, since in either of those
# cases we need to perform a redirection (We do it this way,
# since we'll at most send one redirect back to the client,
# instead of the potential two we might send if we didn't
# combine the checks)
RewriteCond %{HTTP_HOST} !^www\. [OR]
RewriteCond %{ENV:CHANGED} =TRUE
# Capture the non-"www." part of the host, regardless of
# whether or not the "www." is there
RewriteCond %{HTTP_HOST} ^(www\.)?(.*)$
# Redirect anything to the corrected URL, using the
# backreference from the above condition, and the entirety of
# the requested path (possibly modified by the above RewriteRule)
RewriteRule ^.*$ http://www.%2/$0 [R=301,L]
精彩评论