2010-08-21 5 views
6

Toute demande de www.example.com/* doit être redirigé vers www.example.com/blog/*htaccess: Rediriger toutes les demandes à un sous-répertoire, sauf si un répertoire exact existe

Si aucun préfixe www., ajoutez-le. Important: s'il existe un répertoire correspondant à l'URI de la demande, ne pas rediriger.

Exemple:

(www.)example.com/<request> ->www.example.com/blog/<request> sauf <request> === <dirname>

Après les 3 conditions ci-dessus, comment puis-je code un .htaccess? S'il vous plaît aider! Thx ;-)

Répondre

12

Cela devrait faire ce que vous vouliez. J'ai également ajouté un "ne pas rediriger si ce fichier existe", car je n'étais pas sûr de ce qu'il y avait dans vos répertoires existants. Vous pouvez essayer de le supprimer en supprimant le second RewriteCond si vous ne le voulez pas, mais je pense que c'est probablement nécessaire dans une certaine mesure.

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] 
+0

Cela fonctionne bien ... Merci. Hey, probablement si vous pouvez expliquer brièvement à propos de chaque ligne en y ajoutant des commentaires, ce serait mieux. Merci encore de toute façon. –

+1

@Drigit Inrok - C'est un bon point, j'ai ajouté des commentaires maintenant qui, je l'espère, va tout expliquer. –

+0

+1 pour les commentaires – WarFox

Questions connexes