From: Rich Bowen Apache HTTP Server Version 2.2 Available Languages: en This document supplements the The following technique forbids the practice of other sites
+ including your images inline in their pages. This practice is
+ often referred to as "hotlinking", and results in
+ your bandwidth being used to serve content for someone else's
+ site. This technique relies on the value of the
+ There are several ways that you can handle this
+ situation. In this first example, we simply deny the request, if it didn't
+ initiate from a page on our site. For the purpose of this example,
+ we assume that our site is In this second example, instead of failing the request, we display
+ an alternate image instead. In the third example, we redirect the request to an image on some
+ other site. Of these techniques, the last two tend to be the most effective
+ in getting people to stop hotlinking your images, because they will
+ simply not see the image that they expected to see. If all you wish to do is deny access to the resource, rather
+ than redirecting that request elsewhere, this can be
+ accomplished without the use of mod_rewrite:
+ In this recipe, we discuss how to block persistent requests from
+ a particular robot, or user agent. The standard for robot exclusion defines a file,
+ Note that there are methods of accomplishing this which do
+ not use mod_rewrite. Note also that any technique that relies on
+ the clients We use a ruleset that specifies the directory to be
+ protected, and the client In this example, we are blocking a robot called
+
+ Rather than using mod_rewrite for this, you can accomplish the
+ same end using alternate means, as illustrated here:
+
+ As noted above, this technique is trivial to circumvent, by simply
+ modifying the We wish to maintain a blacklist of hosts, rather like
+
+ The second RewriteCond assumes that you have HostNameLookups turned
+ on, so that client IP addresses will be resolved. If that's not the
+ case, you should drop the second RewriteCond, and drop the
+ Redirect requests based on the Referer from which the request
+ came, with different targets per Referer. The following ruleset uses a map file to associate each Referer
+ with a redirection target. The map file lists redirection targets for each referer, or, if
+ we just wish to redirect back to where they came from, a "-" is
+ placed in the map: Available Languages: en This document supplements the The following technique forbids the practice of other sites
+ including your images inline in their pages. This practice is
+ often referred to as "hotlinking", and results in
+ your bandwidth being used to serve content for someone else's
+ site. This technique relies on the value of the
+ There are several ways that you can handle this
+ situation. In this first example, we simply deny the request, if it didn't
+ initiate from a page on our site. For the purpose of this example,
+ we assume that our site is In this second example, instead of failing the request, we display
+ an alternate image instead. In the third example, we redirect the request to an image on some
+ other site. Of these techniques, the last two tend to be the most effective
+ in getting people to stop hotlinking your images, because they will
+ simply not see the image that they expected to see. If all you wish to do is deny access to the resource, rather
+ than redirecting that request elsewhere, this can be
+ accomplished without the use of mod_rewrite:
+ In this recipe, we discuss how to block persistent requests from
+ a particular robot, or user agent. The standard for robot exclusion defines a file,
+ Note that there are methods of accomplishing this which do
+ not use mod_rewrite. Note also that any technique that relies on
+ the clients We use a ruleset that specifies the directory to be
+ protected, and the client In this example, we are blocking a robot called
+
+ Rather than using mod_rewrite for this, you can accomplish the
+ same end using alternate means, as illustrated here:
+
+ As noted above, this technique is trivial to circumvent, by simply
+ modifying the We wish to maintain a blacklist of hosts, rather like
+
+ The second RewriteCond assumes that you have HostNameLookups turned
+ on, so that client IP addresses will be resolved. If that's not the
+ case, you should drop the second RewriteCond, and drop the
+ Redirect requests based on the Referer from which the request
+ came, with different targets per Referer. The following ruleset uses a map file to associate each Referer
+ with a redirection target. The map file lists redirection targets for each referer, or, if
+ we just wish to redirect back to where they came from, a "-" is
+ placed in the map: Apache HTTP Server Version 2.2 Available Languages: en This document supplements the A common technique for distributing the burden of
+ server load or storage space is called "sharding".
+ When using this method, a front-end server will use the
+ url to consistently "shard" users or objects to separate
+ backend servers. A mapping is maintained, from users to target servers, in
+ external map files. They look like: We put this into a to thus every URL path need not be valid on every backend physical
+ host. The following ruleset does this for us with the help of the map
+ files assuming that server0 is a default server which will be used if
+ a user has no entry in the map: We wish to dynamically generate content, but store it
+ statically once it is generated. This rule will check for the
+ existence of the static file, and if it's not there, generate
+ it. The static files can be removed periodically, if desired (say,
+ via cron) and will be regenerated on demand. Here a request for We wish to randomly distribute load across several servers
+ using mod_rewrite. We'll use If you want one particular server to get more of the load than the
+others, add it more times to the list. Apache comes with a load-balancing module -
+ Wouldn't it be nice, while creating a complex web page, if
+ the web browser would automatically refresh the page every
+ time we save a new version from within our editor?
+ Impossible? No! We just combine the MIME multipart feature, the
+ web server NPH feature, and the URL manipulation power of
+ Now when we reference the URL this leads to the internal invocation of the URL The only missing part is the NPH-CGI script. Although
+ one would usually say "left as an exercise to the reader"
+ ;-) I will provide this, too. Some sites with thousands of users use a
+ structured homedir layout, i.e. each homedir is in a
+ subdirectory which begins (for instance) with the first
+ character of the username. So, We use the following ruleset to expand the tilde URLs
+ into the above layout. By default, redirecting to an HTML anchor doesn't work,
+ because mod_rewrite escapes the Use the We wish to use mod_rewrite to serve different content based on
+ the time of day. There are a lot of variables named This provides the content of At time, we want to maintain some kind of status when we
+ perform a rewrite. For example, you want to make a note that
+ you've done that rewrite, so that you can check later to see if a
+ request can via that rewrite. One way to do this is by setting an
+ environment variable. Use the [E] flag to set an environment variable. Later in your ruleset you might check for this environment
+ variable using a RewriteCond: Available Languages: en This document supplements the We wish to dynamically generate content, but store it
+ statically once it is generated. This rule will check for the
+ existence of the static file, and if it's not there, generate
+ it. The static files can be removed periodically, if desired (say,
+ via cron) and will be regenerated on demand. Here a request for We wish to randomly distribute load across several servers
+ using mod_rewrite. We'll use If you want one particular server to get more of the load than the
+others, add it more times to the list. Apache comes with a load-balancing module -
+ Wouldn't it be nice, while creating a complex web page, if
+ the web browser would automatically refresh the page every
+ time we save a new version from within our editor?
+ Impossible? No! We just combine the MIME multipart feature, the
+ web server NPH feature, and the URL manipulation power of
+ Now when we reference the URL this leads to the internal invocation of the URL The only missing part is the NPH-CGI script. Although
+ one would usually say "left as an exercise to the reader"
+ ;-) I will provide this, too. Some sites with thousands of users use a
+ structured homedir layout, i.e. each homedir is in a
+ subdirectory which begins (for instance) with the first
+ character of the username. So, We use the following ruleset to expand the tilde URLs
+ into the above layout. By default, redirecting to an HTML anchor doesn't work,
+ because mod_rewrite escapes the Use the We wish to use mod_rewrite to serve different content based on
+ the time of day. There are a lot of variables named This provides the content of At time, we want to maintain some kind of status when we
+ perform a rewrite. For example, you want to make a note that
+ you've done that rewrite, so that you can check later to see if a
+ request can via that rewrite. One way to do this is by setting an
+ environment variable. Use the [E] flag to set an environment variable. Later in your ruleset you might check for this environment
+ variable using a RewriteCond: Apache HTTP Server Version 2.2 Available Languages: en This document supplements the mod_rewrite should be considered a last resort, when other
+alternatives are found wanting. Using it when there are simpler
+alternatives leads to configurations which are confusing, fragile, and
+hard to maintain. Understanding what other alternatives are available is
+a very important step towards mod_rewrite mastery. Note that many of these examples won't work unchanged in your
+particular server configuration, so it's important that you understand
+them, rather than merely cutting and pasting the examples into your
+configuration. The most common situation in which A common use for These situations are better handled by the To redirect URLs under To redirect The use of In the case of the http-to-https redirection, the use of
+ The
+The use of Symbolic links would be another way to accomplish the same thing, if
+you have Although it is possible to handle virtual hosts
+with mod_rewrite, it is seldom the right way. Creating individual
+<VirtualHost> blocks is almost always the right way to go. In the
+event that you have an enormous number of virtual hosts, consider using
+ Third-party modules such as mod_macro are
+also useful for creating a large number of virtual hosts dynamically. Using See the virtual hosts with mod_rewrite
+document for more details on how you might accomplish this if it still
+seems like the right approach. However, in many cases, when there is no actual pattern matching
+meeded, as in the example shown above, the Note that whether you use You may need to use Consider, for example, the common scenario where
+ This technique can be used to take actions based on any request
+header, response header, or environment variable, replacing
+ See especially the expression evaluation
+documentation for a overview of what types of expressions you can
+use in <If> sections, and in certain other directives. Available Languages: en This document supplements the mod_rewrite should be considered a last resort, when other
+alternatives are found wanting. Using it when there are simpler
+alternatives leads to configurations which are confusing, fragile, and
+hard to maintain. Understanding what other alternatives are available is
+a very important step towards mod_rewrite mastery. Note that many of these examples won't work unchanged in your
+particular server configuration, so it's important that you understand
+them, rather than merely cutting and pasting the examples into your
+configuration. The most common situation in which A common use for These situations are better handled by the To redirect URLs under To redirect The use of In the case of the http-to-https redirection, the use of
+ The
+The use of Symbolic links would be another way to accomplish the same thing, if
+you have Although it is possible to handle virtual hosts
+with mod_rewrite, it is seldom the right way. Creating individual
+<VirtualHost> blocks is almost always the right way to go. In the
+event that you have an enormous number of virtual hosts, consider using
+ Third-party modules such as mod_macro are
+also useful for creating a large number of virtual hosts dynamically. Using See the virtual hosts with mod_rewrite
+document for more details on how you might accomplish this if it still
+seems like the right approach. However, in many cases, when there is no actual pattern matching
+meeded, as in the example shown above, the Note that whether you use You may need to use Consider, for example, the common scenario where
+ This technique can be used to take actions based on any request
+header, response header, or environment variable, replacing
+ See especially the expression evaluation
+documentation for a overview of what types of expressions you can
+use in <If> sections, and in certain other directives. Apache HTTP Server Version 2.2 This document discusses the flags which are available to the
+ A The flags all have a short form, such as Each flag (with a few exceptions)
+has a long and short form. While it is most common to use
+the short form, it is recommended that you familiarize yourself with the
+long form, so that you remember what each flag is supposed to do. Flags that alter metadata associated with the request (T=, H=, E=)
+have no affect in per-directory and htaccess context, when a substitution
+(other than '-') is performed during the same round of rewrite processing.
+ Presented here are each of the available flags, along with an example
+of how you might use them. The [B] flag instructs This will map This escaping is particularly necessary in a proxy situation,
+when the backend may break if presented with an unescaped URL. The [C] or [chain] flag indicates that the The [CO], or [cookie] flag, allows you to set a cookie when a
+particular The full syntax for the flag, including all attributes, is as
+follows: You must declare a name and value for the cookie to be set. You may optionally also set the following values: Several examples are offered here: In the example give, the rule doesn't rewrite the request.
+The "-" rewrite target tells mod_rewrite to pass the request
+through unchanged. Instead, it sets a cookie
+called 'frontdoor' to a value of 'yes'. The cookie is valid for any host
+in the The DPI flag causes the PATH_INFO portion of the rewritten URI to be
+discarded. This flag is available in version 2.2.12 and later. In per-directory context, the URI each The current URI can be the initial URI as requested by the client, the
+result of a previous round of mod_rewrite processing, or the result of
+a prior rule in the current round of mod_rewrite processing. In contrast, the PATH_INFO that is appended to the URI before each
+rule reflects only the value of PATH_INFO before this round of
+mod_rewrite processing. As a consequence, if large portions
+of the URI are matched and copied into a substitution in multiple
+ Use this flag on any substitution where the PATH_INFO that resulted
+from the previous mapping of this request to the filesystem is not of
+interest. This flag permanently forgets the PATH_INFO established
+before this round of mod_rewrite processing began. PATH_INFO will
+not be recalculated until the current round of mod_rewrite processing
+completes. Subsequent rules during this round of processing will see
+only the direct result of substitutions, without any PATH_INFO
+appended. With the [E], or [env] flag, you can set the value of an environment
+variable. Note that some environment variables may be set after the rule
+is run, thus unsetting what you have set. See the
+Environment Variables document for more details on how Environment
+variables work. The full syntax for this flag is: Using the short form you can set the environment variable named The form allows to unset a previously set environment variable named
+ Environment variables can then be used in a variety of
+contexts, including CGI programs, other RewriteRule directives, or
+CustomLog directives. The following example sets an environment variable called 'image' to a
+value of '1' if the requested URI is an image file. Then, that
+environment variable is used to exclude those requests from the access
+log. Note that this same effect can be obtained using Using the [F] flag causes the server to return a 403 Forbidden status
+code to the client. While the same behavior can be accomplished using
+the The following rule will forbid This example uses the "-" syntax for the rewrite target, which means
+that the requested URI is not modified. There's no reason to rewrite to
+another URI, if you're going to forbid the request. When using [F], an [L] is implied - that is, the response is returned
+immediately, and no further rules are evaluated. The [G] flag forces the server to return a 410 Gone status with the
+response. This indicates that a resource used to be available, but is no
+longer available. As with the [F] flag, you will typically use the "-" syntax for the
+rewrite target when using the [G] flag: When using [F], an [L] is implied - that is, the response is returned
+immediately, and no further rules are evaluated. Forces the resulting request to be handled with the specified
+handler. For example, one might use this to force all files without a
+file extension to be parsed by the php handler:
+The regular expression above - This can be also used to force the handler based on some conditions.
+For example, the following snippet used in per-server context allows
+ The regular expression above - The [L] flag causes If you are using It is therefore important, if you are using An alternative flag, [END], can be used to terminate not only the
+current round of rewrite processing but prevent any subsequent
+rewrite processing from occuring in per-directory (htaccess)
+context. This does not apply to new requests resulting from external
+redirects. The example given here will rewrite any request to
+
+The [N] flag causes the ruleset to start over again from the top, using
+the result of the ruleset so far as a starting point. Use
+with extreme caution, as it may result in loop.
+
+The [Next] flag could be used, for example, if you wished to replace a
+certain string or letter repeatedly in a request. The example shown here
+will replace A with B everywhere in a request, and will continue doing
+so until there are no more As to be replaced.
+ You can think of this as a Use of the [NC] flag causes the In the example below, any request for an image file will be proxied
+to your dedicated image server. The match is case-insensitive, so that
+ By default, special characters, such as
+The above example will redirect Use of the [NS] flag prevents the rule from being used on
+subrequests. For example, a page which is included using an SSI (Server
+Side Include) is a subrequest, and you may want to avoid rewrites
+happening on those subrequests. Also, when To decide whether or not to use this rule: if you prefix URLs with
+CGI-scripts, to force them to be processed by the CGI-script, it's
+likely that you will run into problems (or significant overhead)
+on sub-requests. In these cases, use this flag.
+Images, javascript files, or css files, loaded as part of an HTML page,
+are not subrequests - the browser requests them as separate HTTP
+requests.
+ Use of the [P] flag causes the request to be handled by
+ Use of the [P] flag implies [L] - that is, the request is immediately
+pushed through the proxy, and any following rules will not be
+considered.
+You must make sure that the substitution string is a valid URI
+(typically starting with Note:
+The target (or substitution string) in a RewriteRule is assumed to be a
+file path, by default. The use of the [PT] flag causes it to be treated
+as a URI instead. That is to say, the
+use of the [PT] flag causes the result of the
+If, for example, you have an
+
+Omission of the [PT] flag in this case will cause the Alias to be
+ignored, resulting in a 'File not found' error being returned.
+ The Note that the
+When the replacement URI contains a query string, the default behavior
+of Consider the following rule: With the [QSA] flag, a request for
+When the requested URI contains a query string, and the target URI does
+not, the default behavior of This flag is available in version 2.4.0 and later.
+Using [QSD] and [QSA] together will result in [QSD] taking precedence.
+
+If the target URI has a query string, the default behavior will be
+observed - that is, the original query string will be discarded and
+replaced with the query string in the
+Use of the [R] flag causes a HTTP redirect to be issued to the browser.
+If a fully-qualified URL is specified (that is, including
+
+Any valid HTTP response status code may be specified,
+using the syntax [R=305], with a 302 status code being used by
+default if none is specified. The status code specified need not
+necessarily be a redirect (3xx) status code.
+ If a status code is outside the redirect range (300-399) then the
+substitution string is dropped entirely, and rewriting is stopped as if
+the In addition to response status codes, you may also specify redirect
+status using their symbolic names:
+You will almost always want to use [R] in conjunction with [L] (that is,
+use [R,L]) because on its own, the [R] flag prepends
+ The [S] flag is used to skip rules that you don't want to run. This
+can be thought of as a This technique is useful because a Sets the MIME type with which the resulting response will be
+sent. This has the same effect as the For example, you might use the following technique to serve Perl
+source code as plain text, if requested in a particular way: Or, perhaps, if you have a camera that produces jpeg images without
+file extensions, you could force those images to be served with the
+correct MIME type by virtue of their file names: Please note that this is a trivial example, and could be better done
+using
+If used in per-directory context, use only Serveur Apache HTTP Version 2.2 Ce document décrit les drapeaux disponibles dans la directive
+ Le comportement d'une directive Les drapeaux ont tous une forme courte, comme Chaque drapeau (à quelques exceptions près) possède une forme longue et une forme courte. Bien que
+la forme courte soit la plus couramment utilisée, nous vous recommandons
+de vous familiariser avec les drapeaux sous leur forme longue, afin de
+bien mémoriser ce que chaque drapeau est supposé faire. Les drapeaux qui modifient les métadonnées associées à la requête
+(T=, H=, E=) n'ont aucun effet dans un contexte de répertoire ou de
+fichier htaccess, lorsqu'une substitution (autre que '-') est effectuée
+au cours de la même passe du processus de réécriture.
+ Chaque drapeau disponible est présenté ici, avec un exemple
+d'utilisation. Avec le drapeau [B], la directive Avec cet exemple, Ce processus d'échappement est en particulier nécessaire dans le
+contexte d'un mandataire, où l'accès au serveur d'arrière-plan échouera
+si on présente à ce dernier une URL non échappée. Le drapeau [C] ou [chain] indique que la règle Le drapeau [CO], ou [cookie], vous permet de définir un cookie
+lorsqu'une règle La syntaxe complète de ce drapeau, avec tous ses attributs, est la
+suivante : Vous devez déclarer un nom et une valeur pour que le cookie puisse
+être défini. Vous pouvez aussi définir les valeurs suivantes : Voici un exemple : Dans l'exemple ci-dessus, la règle ne réécrit
+pas la requête. La cible de réécriture "-"
+indique à mod_rewrite de transmettre la requête sans
+modification. Par contre, il
+définit un cookie nommé 'frontdoor' avec une valeur 'yes'. Le cookie est
+valide pour tout hôte situé dans le domaine Avec le drapeau DPI, la partie PATH_INFO de l'URI
+réécrit est supprimée. Ce drapeau est disponible dans les versions 2.2.12 et supérieures. Dans un contexte de répertoire, l'URI mis en comparaison par chaque
+règle L'URI courant peut être l'URI initial tel qu'il a été fourni par le
+client, le résultat d'une passe précédente du processus de réécriture,
+ou le résultat de la règle précédente dans le processus courant de
+réécriture. Par contre, la partie PATH_INFO ajoutée à l'URI avant chaque règle ne
+reflète que la valeur de PATH_INFO avant la passe courante du processus
+de réécriture. En conséquence, si de larges portions de l'URI
+correspondent et sont traduites via plusieurs directives
+ Utilisez ce drapeau pour toute substitution où la présence du PATH_INFO qui
+résultait de la mise en correspondance précédente de cette requête avec
+le système de fichier n'est pas nécessaire. Avec ce drapeau, le
+PATH_INFO établi avant que cette passe du processus de réécriture ne
+débute est oublié. PATH_INFO ne sera pas recalculé tant que la passe
+courante du processus de réécriture ne sera pas achevée. Les règles
+suivantes de cette passe ne verront que le résultat direct des
+substitutions, sans aucun PATH_INFO ajouté. Avec le drapeau [E], ou [env], vous pouvez définir la valeur d'une
+variable d'environnement. Notez que certaines variables d'environnement
+peuvent être définies après le traitement de la règle, annulant par
+la-même ce que vous avez défini. Voir le document
+sur les variables d'environnement pour plus de détails sur le
+fonctionnement des variables d'environnement. La syntaxe complète pour ce drapeau est : En utilisant la version courte vous pouvez définir la variable d'environnement nommée
+ La forme permet d'annuler la définition de la variable Les variables d'environnement s'emploient dans différents contextes,
+comme les programmes CGI, d'autres directives RewriteRule, ou des
+directives CustomLog. L'exemple suivant définit une variable d'environnement nommée 'image'
+avec une valeur de '1' si l'URI de la requête correspond à un fichier
+image. Cette variable d'environnement est ensuite utilisée pour exclure
+une telle requête du journal des accès. Notez que le même effet peut être obtenu à l'aide de la directive
+ L'utilisation du drapeau [F] permet de faire envoyer par le serveur au
+client un code de statut "403 Forbidden". Le même effet peut être obtenu à
+l'aide de la directive La règle suivante va interdire la téléchargement de fichiers
+ Cet exemple utilise la syntaxe "-" pour la cible de réécriture, ce
+qui signifie que l'URI de la requête n'est pas modifié. Il n'y a aucune
+raison de réécrire un URI, si vous avez l'intention d'interdire la
+requête. Lorsqu'on utilise [F], [L] est implicite - c'est à dire que la
+réponse est renvoyée immédiatement, et aucune autre règle n'est évaluée. Le drapeau [G] permet de faire envoyer par le serveur un code de statut
+"410 Gone" avec la réponse. Ce code indique qu'une ressource qui était
+disponible auparavant ne l'est plus actuellement. Comme dans le cas du drapeau [F], on utilise en général la syntaxe
+"-" pour la cible de réécriture lorsqu'on utilise le drapeau [G] : Lorsqu'on utilise [F], [L] est implicite - c'est à dire que la
+réponse est renvoyée immédiatement, et aucune autre règle n'est évaluée. Force le traitement de la requête résultante par le gestionnaire
+spécifié. Par exemple, on peut utiliser ce drapeau pour forcer
+l'interprétation de tous les fichiers sans extension par le gestionnaire
+php :
+L'expression rationnelle ci-dessus - On peut aussi utiliser ce drapeau pour forcer l'utilisation d'un
+certain gestionnaire en fonction de certaines conditions. Par exemple,
+l'extrait suivant utilisé dans un contexte de niveau serveur permet de
+faire en sorte que les fichiers L'expression rationnelle ci-dessus -
+ Lorsque le drapeau [L] est présent, Si vous utilisez des règles Si vous utilisez des directives Un autre drapeau, [END], permet non seulement d'interrompre le cycle
+courant du processus de réécriture, mais aussi d'empêcher toute
+réécriture ultérieure dans le contexte de répertoire (htaccess). Ceci ne
+s'applique pas aux nouvelles requêtes résultant de redirections
+externes. Dans l'exemple donné ici, toute requête est réécrite en
+ Le drapeau [N] provoque un redémarrage du traitement des règles
+depuis le début, en utilisant le résultat du jeu de règles, sous
+réserve qu'il existe un point de démarrage ; à utiliser avec précautions
+car il peut provoquer un bouclage infini.
+
+Le drapeau [Next] peut servir, par exemple,
+à remplacer de manière répétitive
+une chaîne de caractère ou une lettre dans une requête. Dans l'exemple
+suivant, chaque occurence de A sera remplacée par B dans la requête, et
+ceci jusqu'il n'y ait plus de A à remplacer.
+ Vous pouvez vous représenter ce traitement comme une boucle
+ Avec le drapeau [NC], le modèle de la règle Dans l'exemple suivant, toute requête pour un fichier image sera
+transmise par Apache à votre serveur d'images dédié. La correspondance est
+insensible à la casse, si bien que par exemple, Par défaut, les caractères spéciaux, comme
+Dans l'exemple ci-dessus, Le drapeau [NS] empêche la règle de s'appliquer aux sous-requêtes.
+Par exemple, une page incluse au moyen d'une SSI (Server
+Side Include) est une sous-requête, et vous ne voudrez probablement pas que
+la réécriture s'applique à ces sous-requêtes. Ainsi, lorsque
+ Comment déterminer si vous devez utiliser cette règle ou non : si
+vous préfixez les URLs avec des scripts CGI, afin de forcer leur
+traitement par le script CGI, vous vous exposez à des problèmes (ou du
+moins à une surcharge significative) avec les sous-requêtes. Dans ces
+cas, vous devez utiliser ce drapeau.
+Les images, scripts java, ou fichiers css, chargés en tant que partie
+d'une page html, ne sont pas des sous-requêtes - le navigateur les
+appelle sous forme de requêtes HTTP à part entière.
+ L'utilisation du drapeau [P] entraîne le traitement de la requête par
+le module L'utilisation du drapeau [P] provoque aussi l'effet du drapeau [L] -
+autrement dit, la requête est immédiatement envoyée au mandataire, et
+toute règle ultérieure sera ignorée.
+Vous devez vous assurer que la chaîne de substitution soit un URI valide
+(commençant typiquement par Note:
+Par défaut, la cible (ou chaîne de substitution) d'une règle
+RewriteRule est sensée être un chemin de fichier. Avec le drapeau [PT],
+par contre, elle est traitée comme un URI. Autrement dit, avec le
+drapeau [PT], le résultat de la règle
+Si par exemple, vous avez un
+Dans l'exemple précédent, en l'absence du drapeau [PT], l'Alias aurait
+été ignoré, ce qui aurait provoqué une erreur 'File not found'.
+ Avec le drapeau Notez que le drapeau
+Quand l'URI de remplacement contient une chaîne de requête, le
+comportement par défaut de la règle Considérons la règle suivante : Avec le drapeau [QSA], une requête pour
+
+Lorsque l'URI de la requête contient une chaîne de paramètres, et si
+l'URI cible n'en contient pas, le comportement par défaut de la
+directive Ce drapeau est disponible dans les versions 2.4.0 et supérieures.
+Lorsque les drapeaux [QSD] et [QSA] sont utilisés ensemble, c'est le
+drapeau [QSD] qui l'emporte.
+
+Si l'URI cible possède une chaîne de paramètres, le comportement par
+défaut sera respecté - c'est à dire que la chaîne de paramètres
+originale sera supprimée et remplacée par la chaîne de paramètres de
+l'URI cible.
+
+L'utilisation du drapeau [R] provoque l'envoi d'une redirection au
+navigateur. Si une URL pleinement qualifiée (FQDN - fully qualified domain name)
+ est spécifiée (c'est à dire incluant Tout code de statut de réponse HTTP valide peut être
+spécifié, en utilisant la syntaxe [R=305], le code de statut 302 étant
+utilisé par défaut si aucun code n'est spécifié. Le code de statut
+spécifié n'est pas nécessairement un code de statut de redirection (3xx).
+ Si le code de statut est en dehors de la plage des codes de
+redirection (300-399), la chaîne de substitution est entièrement
+supprimée, et la réécriture s'arrête comme si le drapeau En plus des codes de statut de réponse, vous pouvez spécifier les
+codes de redirection en utilisant leurs noms symboliques :
+
+Vous utiliserez presque toujours [R] en conjonction avec [L] (c'est à
+dire [R,L]), car employé seul, le drapeau [R] préfixe l'URI avec
+ Le drapeau [S] sert à sauter des règles que vous ne voulez pas voir
+exécuter. Ceci peut s'interpréter comme une instruction
+ Cette technique trouve son utilité dans le fait qu'une directive
+ Définit le type MIME de la réponse résultante renvoyée. L'effet est
+identique à celui de la directive Par exemple, vous pouvez utiliser la technique suivante pour servir
+du code source Perl en tant que plein texte, s'il est requis d'une
+certaine manière : Ou encore, si vous possédez une caméra qui produit des fichiers
+images jpeg sans extension, vous pouvez forcer le renvoi de ces images
+avec le type MIME correct en se basant sur le nom du fichier : Notez cependant qu'il s'agit d'un exemple trivial, et que le problème
+aurait pu être résolu en utilisant à la place la directive
+Dans un contexte de niveau répertoire, n'utilisez que This document discusses the flags which are available to the

Using mod_rewrite to control access
+mod_rewrite
+reference documentation. It describes
+how you can use mod_rewrite to control access to
+various resources, and other related techniques.
+This includes many examples of common uses of mod_rewrite,
+including detailed descriptions of how each works.
Forbidding Image "Hotlinking"
Blocking of Robots
Denying Hosts in a Blacklist
Referer-based DeflectorSee also
Forbidding Image "Hotlinking"
+
+
+
+
+
+
+ HTTP_REFERER variable, which is optional. As
+ such, it's possible for some people to circumvent this
+ limitation. However, most users will experience the failed
+ request, which should, over time, result in the image being
+ removed from that other site.www.example.com.
+RewriteCond %{HTTP_REFERER} !^$
+RewriteCond %{HTTP_REFERER} !www.example.com [NC]
+RewriteRule \.(gif|jpg|png)$ - [F,NC]
+
+RewriteCond %{HTTP_REFERER} !^$
+RewriteCond %{HTTP_REFERER} !www.example.com [NC]
+RewriteRule \.(gif|jpg|png)$ /images/go-away.png [R,NC]
+
+RewriteCond %{HTTP_REFERER} !^$
+RewriteCond %{HTTP_REFERER} !www.example.com [NC]
+RewriteRule \.(gif|jpg|png)$ http://other.example.com/image.gif [R,NC]
+
+ SetEnvIf Referer example\.com localreferer
+ <FilesMatch \.(jpg|png|gif)$>
+ Order deny,allow
+ Deny from all
+ Allow from env=localreferer
+ </FilesMatch>
+ Blocking of Robots
+
+
+
+
+
+
+ /robots.txt that specifies those portions of your
+ website where you which to exclude robots. However, some robots
+ do not honor these files.
+ USER_AGENT string can be circumvented
+ very easily, since that string can be changed.USER_AGENT that
+ identifies the malicious or persistent robot.NameOfBadRobot from a location
+ /secret/files. You may also specify an IP address
+ range, if you are trying to block that user agent only from the
+ particular source.
+RewriteCond %{HTTP_USER_AGENT} ^NameOfBadRobot
+RewriteCond %{REMOTE_ADDR} =123\.45\.67\.[8-9]
+RewriteRule ^/secret/files/ - [F]
+
+ SetEnvIfNoCase User-Agent ^NameOfBadRobot goaway
+ <Location /secret/files>
+ Order allow,deny
+ Allow from all
+ Deny from env=goaway
+ </Location>
+ USER_AGENT request header. If you
+ are experiencing a sustained attack, you should consider blocking
+ it at a higher level, such as at your firewall.
+ Denying Hosts in a Blacklist
+
+
+
+
+
+
+hosts.deny, and have those hosts blocked from
+ accessing our server.
+RewriteEngine on
+RewriteMap hosts-deny txt:/path/to/hosts.deny
+RewriteCond ${hosts-deny:%{REMOTE_ADDR}|NOT-FOUND} !=NOT-FOUND [OR]
+RewriteCond ${hosts-deny:%{REMOTE_HOST}|NOT-FOUND} !=NOT-FOUND
+RewriteRule ^ - [F]
+
+##
+## hosts.deny
+##
+## ATTENTION! This is a map, not a list, even when we treat it as such.
+## mod_rewrite parses it for key/value pairs, so at least a
+## dummy value "-" must be present for each entry.
+##
+
+193.102.180.41 -
+bsdti1.sdm.de -
+192.76.162.40 -
+[OR] flag from the first RewriteCond.
+ Referer-based Deflector
+
+
+
+
+
+
+
+RewriteMap deflector txt:/path/to/deflector.map
+
+RewriteCond %{HTTP_REFERER} !=""
+RewriteCond ${deflector:%{HTTP_REFERER}} =-
+RewriteRule ^ %{HTTP_REFERER} [R,L]
+
+RewriteCond %{HTTP_REFERER} !=""
+RewriteCond ${deflector:%{HTTP_REFERER}|NOT-FOUND} !=NOT-FOUND
+RewriteRule ^.* ${deflector:%{HTTP_REFERER}} [R,L]
+
+##
+## deflector.map
+##
+
+http://badguys.example.com/bad/index.html -
+http://badguys.example.com/bad/index2.html -
+http://badguys.example.com/bad/index3.html http://somewhere.example.com/
+
+
+
+ HTTP_REFERER variable, which is optional. As
+ such, it's possible for some people to circumvent this
+ limitation. However, most users will experience the failed
+ request, which should, over time, result in the image being
+ removed from that other site.www.example.com.
+RewriteCond %{HTTP_REFERER} !www.example.com [NC]
+RewriteRule \.(gif|jpg|png)$ - [F,NC]
+
+RewriteCond %{HTTP_REFERER} !www.example.com [NC]
+RewriteRule \.(gif|jpg|png)$ /images/go-away.png [R,NC]
+
+RewriteCond %{HTTP_REFERER} !www.example.com [NC]
+RewriteRule \.(gif|jpg|png)$ http://other.example.com/image.gif [R,NC]
+
+ <FilesMatch \.(jpg|png|gif)$>
+ Order deny,allow
+ Deny from all
+ Allow from env=localreferer
+ </FilesMatch>
+
+
+
+ /robots.txt that specifies those portions of your
+ website where you which to exclude robots. However, some robots
+ do not honor these files.
+ USER_AGENT string can be circumvented
+ very easily, since that string can be changed.USER_AGENT that
+ identifies the malicious or persistent robot.NameOfBadRobot from a location
+ /secret/files. You may also specify an IP address
+ range, if you are trying to block that user agent only from the
+ particular source.
+RewriteCond %{REMOTE_ADDR} =123\.45\.67\.[8-9]
+RewriteRule ^/secret/files/ - [F]
+
+ <Location /secret/files>
+ Order allow,deny
+ Allow from all
+ Deny from env=goaway
+ </Location>
+ USER_AGENT request header. If you
+ are experiencing a sustained attack, you should consider blocking
+ it at a higher level, such as at your firewall.
+
+
+
+hosts.deny, and have those hosts blocked from
+ accessing our server.
+RewriteMap hosts-deny txt:/path/to/hosts.deny
+RewriteCond ${hosts-deny:%{REMOTE_ADDR}|NOT-FOUND} !=NOT-FOUND [OR]
+RewriteCond ${hosts-deny:%{REMOTE_HOST}|NOT-FOUND} !=NOT-FOUND
+RewriteRule ^ - [F]
+
+## hosts.deny
+##
+## ATTENTION! This is a map, not a list, even when we treat it as such.
+## mod_rewrite parses it for key/value pairs, so at least a
+## dummy value "-" must be present for each entry.
+##
+
+193.102.180.41 -
+bsdti1.sdm.de -
+192.76.162.40 -
+[OR] flag from the first RewriteCond.
+
+
+
+
+
+RewriteCond %{HTTP_REFERER} !=""
+RewriteCond ${deflector:%{HTTP_REFERER}} =-
+RewriteRule ^ %{HTTP_REFERER} [R,L]
+
+RewriteCond %{HTTP_REFERER} !=""
+RewriteCond ${deflector:%{HTTP_REFERER}|NOT-FOUND} !=NOT-FOUND
+RewriteRule ^.* ${deflector:%{HTTP_REFERER}} [R,L]
+
+## deflector.map
+##
+
+http://badguys.example.com/bad/index.html -
+http://badguys.example.com/bad/index2.html -
+http://badguys.example.com/bad/index3.html http://somewhere.example.com/
+
Advanced Techniques with mod_rewrite
+mod_rewrite
+reference documentation. It provides
+a few advanced techniques and tricks using mod_rewrite.
URL-based sharding accross multiple backends
On-the-fly Content-Regeneration
Load Balancing
Document With Autorefresh
Structured Userdirs
Redirecting Anchors
Time-Dependent Rewriting
Set Environment Variables Based On URL PartsSee also
URL-based sharding accross multiple backends
+
+
+
+
+
+
+
+user1 physical_host_of_user1
+user2 physical_host_of_user2
+: :
+map.users-to-hosts file. The
+ aim is to map;
+/u/user1/anypath
+
+http://physical_host_of_user1/u/user/anypath
+
+RewriteEngine on
+
+RewriteMap users-to-hosts txt:/path/to/map.users-to-hosts
+
+RewriteRule ^/u/([^/]+)/?(.*) http://${users-to-hosts:$1|server0}/u/$1/$2
+On-the-fly Content-Regeneration
+
+
+
+
+
+
+
+# This example is valid in per-directory context only
+RewriteCond %{REQUEST_FILENAME} !-s
+RewriteRule ^page\.html$ page.cgi [T=application/x-httpd-cgi,L]
+page.html leads to an
+ internal run of a corresponding page.cgi if
+ page.html is missing or has filesize
+ null. The trick here is that page.cgi is a
+ CGI script which (additionally to its STDOUT)
+ writes its output to the file page.html.
+ Once it has completed, the server sends out
+ page.html. When the webmaster wants to force
+ a refresh of the contents, he just removes
+ page.html (typically from cron).Load Balancing
+
+
+
+
+
+
+RewriteMap and a list of servers
+ to accomplish this.
+RewriteEngine on
+RewriteMap lb rnd:/path/to/serverlist.txt
+
+RewriteRule ^/(.*) http://${lb:servers}/$1 [P,L]
+serverlist.txt will contain a list of the servers:
+## serverlist.txt
+
+servers one.example.com|two.example.com|three.example.com
+mod_proxy_balancer - which is far more flexible and
+featureful than anything you can cobble together using mod_rewrite.Document With Autorefresh
+
+
+
+
+
+
+mod_rewrite. First, we establish a new
+ URL feature: Adding just :refresh to any
+ URL causes the 'page' to be refreshed every time it is
+ updated on the filesystem.
+RewriteRule ^(/[uge]/[^/]+/?.*):refresh /internal/cgi/apache/nph-refresh?f=$1
+
+/u/foo/bar/page.html:refresh
+
+/internal/cgi/apache/nph-refresh?f=/u/foo/bar/page.html
+
+#!/sw/bin/perl
+##
+## nph-refresh -- NPH/CGI script for auto refreshing pages
+## Copyright (c) 1997 Ralf S. Engelschall, All Rights Reserved.
+##
+$| = 1;
+
+# split the QUERY_STRING variable
+@pairs = split(/&/, $ENV{'QUERY_STRING'});
+foreach $pair (@pairs) {
+($name, $value) = split(/=/, $pair);
+$name =~ tr/A-Z/a-z/;
+$name = 'QS_' . $name;
+$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
+eval "\$$name = \"$value\"";
+}
+$QS_s = 1 if ($QS_s eq '');
+$QS_n = 3600 if ($QS_n eq '');
+if ($QS_f eq '') {
+print "HTTP/1.0 200 OK\n";
+print "Content-type: text/html\n\n";
+print "<b>ERROR</b>: No file given\n";
+exit(0);
+}
+if (! -f $QS_f) {
+print "HTTP/1.0 200 OK\n";
+print "Content-type: text/html\n\n";
+print "<b>ERROR</b>: File $QS_f not found\n";
+exit(0);
+}
+
+sub print_http_headers_multipart_begin {
+print "HTTP/1.0 200 OK\n";
+$bound = "ThisRandomString12345";
+print "Content-type: multipart/x-mixed-replace;boundary=$bound\n";
+&print_http_headers_multipart_next;
+}
+
+sub print_http_headers_multipart_next {
+print "\n--$bound\n";
+}
+
+sub print_http_headers_multipart_end {
+print "\n--$bound--\n";
+}
+
+sub displayhtml {
+local($buffer) = @_;
+$len = length($buffer);
+print "Content-type: text/html\n";
+print "Content-length: $len\n\n";
+print $buffer;
+}
+
+sub readfile {
+local($file) = @_;
+local(*FP, $size, $buffer, $bytes);
+($x, $x, $x, $x, $x, $x, $x, $size) = stat($file);
+$size = sprintf("%d", $size);
+open(FP, "<$file");
+$bytes = sysread(FP, $buffer, $size);
+close(FP);
+return $buffer;
+}
+
+$buffer = &readfile($QS_f);
+&print_http_headers_multipart_begin;
+&displayhtml($buffer);
+
+sub mystat {
+local($file) = $_[0];
+local($time);
+
+($x, $x, $x, $x, $x, $x, $x, $x, $x, $mtime) = stat($file);
+return $mtime;
+}
+
+$mtimeL = &mystat($QS_f);
+$mtime = $mtime;
+for ($n = 0; $n < $QS_n; $n++) {
+while (1) {
+ $mtime = &mystat($QS_f);
+ if ($mtime ne $mtimeL) {
+ $mtimeL = $mtime;
+ sleep(2);
+ $buffer = &readfile($QS_f);
+ &print_http_headers_multipart_next;
+ &displayhtml($buffer);
+ sleep(5);
+ $mtimeL = &mystat($QS_f);
+ last;
+ }
+ sleep($QS_s);
+}
+}
+
+&print_http_headers_multipart_end;
+
+exit(0);
+
+##EOF##
+Structured Userdirs
+
+
+
+
+
+
+/~larry/anypath
+ is /home/l/larry/public_html/anypath
+ while /~waldo/anypath is
+ /home/w/waldo/public_html/anypath.
+RewriteEngine on
+RewriteRule ^/~(([a-z])[a-z0-9]+)(.*) /home/$2/$1/public_html$3
+Redirecting Anchors
+
+
+
+
+
+
+# character,
+ turning it into %23. This, in turn, breaks the
+ redirection.[NE] flag on the
+ RewriteRule. NE stands for No Escape.
+ Time-Dependent Rewriting
+
+
+
+
+
+
+TIME_xxx
+ for rewrite conditions. In conjunction with the special
+ lexicographic comparison patterns <STRING,
+ >STRING and =STRING we can
+ do time-dependent redirects:
+RewriteEngine on
+RewriteCond %{TIME_HOUR}%{TIME_MIN} >0700
+RewriteCond %{TIME_HOUR}%{TIME_MIN} <1900
+RewriteRule ^foo\.html$ foo.day.html [L]
+RewriteRule ^foo\.html$ foo.night.html
+foo.day.html
+ under the URL foo.html from
+ 07:01-18:59 and at the remaining time the
+ contents of foo.night.html.mod_cache, intermediate proxies
+ and browsers may each cache responses and cause the either page to be
+ shown outside of the time-window configured.
+ mod_expires may be used to control this
+ effect. You are, of course, much better off simply serving the
+ content dynamically, and customizing it based on the time of day.Set Environment Variables Based On URL Parts
+
+
+
+
+
+
+
+RewriteEngine on
+RewriteRule ^/horse/(.*) /pony/$1 [E=rewritten:1]
+
+RewriteCond %{ENV:rewritten} =1
+
+
+
+
+RewriteCond %{REQUEST_FILENAME} !-s
+RewriteRule ^page\.html$ page.cgi [T=application/x-httpd-cgi,L]
+page.html leads to an
+ internal run of a corresponding page.cgi if
+ page.html is missing or has filesize
+ null. The trick here is that page.cgi is a
+ CGI script which (additionally to its STDOUT)
+ writes its output to the file page.html.
+ Once it has completed, the server sends out
+ page.html. When the webmaster wants to force
+ a refresh of the contents, he just removes
+ page.html (typically from cron).
+
+
+
+RewriteMap lb rnd:/path/to/serverlist.txt
+
+RewriteRule ^/(.*) http://${lb:servers}/$1 [P,L]
+serverlist.txt will contain a list of the servers:
+
+servers one.example.com|two.example.com|three.example.com
+
+
+
+:refresh to any
+ URL causes the 'page' to be refreshed every time it is
+ updated on the filesystem.
+#!/sw/bin/perl
+##
+## nph-refresh -- NPH/CGI script for auto refreshing pages
+## Copyright (c) 1997 Ralf S. Engelschall, All Rights Reserved.
+##
+$| = 1;
+
+# split the QUERY_STRING variable
+@pairs = split(/&/, $ENV{'QUERY_STRING'});
+foreach $pair (@pairs) {
+($name, $value) = split(/=/, $pair);
+$name =~ tr/A-Z/a-z/;
+$name = 'QS_' . $name;
+$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
+eval "\$$name = \"$value\"";
+}
+$QS_s = 1 if ($QS_s eq '');
+$QS_n = 3600 if ($QS_n eq '');
+if ($QS_f eq '') {
+print "HTTP/1.0 200 OK\n";
+print "Content-type: text/html\n\n";
+print "<b>ERROR</b>: No file given\n";
+exit(0);
+}
+if (! -f $QS_f) {
+print "HTTP/1.0 200 OK\n";
+print "Content-type: text/html\n\n";
+print "<b>ERROR</b>: File $QS_f not found\n";
+exit(0);
+}
+
+sub print_http_headers_multipart_begin {
+print "HTTP/1.0 200 OK\n";
+$bound = "ThisRandomString12345";
+print "Content-type: multipart/x-mixed-replace;boundary=$bound\n";
+&print_http_headers_multipart_next;
+}
+
+sub print_http_headers_multipart_next {
+print "\n--$bound\n";
+}
+
+sub print_http_headers_multipart_end {
+print "\n--$bound--\n";
+}
+
+sub displayhtml {
+local($buffer) = @_;
+$len = length($buffer);
+print "Content-type: text/html\n";
+print "Content-length: $len\n\n";
+print $buffer;
+}
+
+sub readfile {
+local($file) = @_;
+local(*FP, $size, $buffer, $bytes);
+($x, $x, $x, $x, $x, $x, $x, $size) = stat($file);
+$size = sprintf("%d", $size);
+open(FP, "<$file");
+$bytes = sysread(FP, $buffer, $size);
+close(FP);
+return $buffer;
+}
+
+$buffer = &readfile($QS_f);
+&print_http_headers_multipart_begin;
+&displayhtml($buffer);
+
+sub mystat {
+local($file) = $_[0];
+local($time);
+
+($x, $x, $x, $x, $x, $x, $x, $x, $x, $mtime) = stat($file);
+return $mtime;
+}
+
+$mtimeL = &mystat($QS_f);
+$mtime = $mtime;
+for ($n = 0; $n < $QS_n; $n++) {
+while (1) {
+ $mtime = &mystat($QS_f);
+ if ($mtime ne $mtimeL) {
+ $mtimeL = $mtime;
+ sleep(2);
+ $buffer = &readfile($QS_f);
+ &print_http_headers_multipart_next;
+ &displayhtml($buffer);
+ sleep(5);
+ $mtimeL = &mystat($QS_f);
+ last;
+ }
+ sleep($QS_s);
+}
+}
+
+&print_http_headers_multipart_end;
+
+exit(0);
+
+##EOF##
+
+
+
+/~larry/anypath
+ is /home/l/larry/public_html/anypath
+ while /~waldo/anypath is
+ /home/w/waldo/public_html/anypath.
+RewriteRule ^/~(([a-z])[a-z0-9]+)(.*) /home/$2/$1/public_html$3
+
+
+
+# character,
+ turning it into %23. This, in turn, breaks the
+ redirection.[NE] flag on the
+ RewriteRule. NE stands for No Escape.
+
+
+
+TIME_xxx
+ for rewrite conditions. In conjunction with the special
+ lexicographic comparison patterns <STRING,
+ >STRING and =STRING we can
+ do time-dependent redirects:
+RewriteCond %{TIME_HOUR}%{TIME_MIN} >0700
+RewriteCond %{TIME_HOUR}%{TIME_MIN} <1900
+RewriteRule ^foo\.html$ foo.day.html [L]
+RewriteRule ^foo\.html$ foo.night.html
+foo.day.html
+ under the URL foo.html from
+ 07:01-18:59 and at the remaining time the
+ contents of foo.night.html.
+
+
+
+RewriteRule ^/horse/(.*) /pony/$1 [E=rewritten:1]
+
When not to use mod_rewrite
+mod_rewrite
+reference documentation. It describes
+perhaps one of the most important concepts about mod_rewrite - namely,
+when to avoid using it.mod_rewrite is
+the right tool is when the very best solution requires access to the
+server configuration files, and you don't have that access. Some
+configuration directives are only available in the server configuration
+file. So if you are in a hosting situation where you only have .htaccess
+files to work with, you may need to resort to
+mod_rewrite.
Simple Redirection
URL Aliasing
Virtual Hosting
Simple Proxying
Environment Variable TestingSee also
Simple Redirection
+
+
+mod_alias provides the Redirect and RedirectMatch directives, which provide a
+means to redirect one URL to another. This kind of simple redirection of
+one URL, or a class of URLs, to somewhere else, should be accomplished
+using these directives rather than RewriteRule. RedirectMatch
+allows you to include a regular expression in your redirection criteria,
+providing many of the benefits of using RewriteRule.RewriteRule is to redirect an entire
+class of URLs. For example, all URLs in the /one directory
+must be redirected to http://one.example.com/, or perhaps
+all http requests must be redirected to
+https.Redirect
+directive. Remember that Redirect preserves path
+information. That is to say, a redirect for a URL /one will
+also redirect all URLs under that, such as /one/two.html
+and /one/three/four.html./one to
+http://one.example.com, do the following:
+Redirect /one/ http://one.example.com/
+http URLs to https, do the
+following:
+<VirtualHost *:80>
+ServerName www.example.com
+Redirect / https://www.example.com/
+</VirtualHost >
+
+<VirtualHost *:443>
+ServerName www.example.com
+
+# ... SSL configuration goes here
+</VirtualHost >
+RewriteRule to perform this task may be
+appropriate if there are other RewriteRule directives in
+the same scope. This is because, when there are Redirect
+and RewriteRule directives in the same scope, the
+RewriteRule directives will run first, regardless of the
+order of appearance in the configuration file.RewriteRule would be appropriate if you don't have access
+to the main server configuration file, and are obliged to perform this
+task in a .htaccess file instead.URL Aliasing
+Alias directive
+provides mapping from a URI to a directory - usually a directory outside
+of your DocumentRoot. Although it
+is possible to perform this mapping with mod_rewrite,
+Alias is the preferred method, for reasons of simplicity
+and performance.Using Alias
+Alias /cats /var/www/virtualhosts/felines/htdocs
+mod_rewrite to perform this mapping may be
+appropriate when you do not have access to the server configuration
+files. Alias may only be used in server or virtualhost context, and not
+in a .htaccess file.
+Options FollowSymLinks enabled on your
+server.Virtual Hosting
+mod_vhost_alias to create these hosts automatically.mod_rewrite for vitualhost creation may be
+appropriate if you are using a hosting service that does not provide
+you access to the server configuration files, and you are therefore
+restricted to configuration using .htaccess files.Simple Proxying
+
+RewriteRule provides the [P] flag to pass rewritten URIs through
+mod_proxy.
+RewriteRule ^/?images(.*) http://imageserver.local/images$1 [P]
+ProxyPass directive is a better choice.
+The example here could be rendered as:
+ProxyPass /images/ http://imageserver.local/images/
+RewriteRule or ProxyPass, you'll still need to use the
+ProxyPassReverse directive to
+catch redirects issued from the back-end server:
+ProxyPassReverse /images/ http://imageserver.local/images/
+RewriteRule instead when there are
+other RewriteRules in effect in the same scope, as a
+RewriteRule will usually take effect before a
+ProxyPass, and so may preempt what you're trying to
+accomplish.Environment Variable Testing
+
+mod_rewrite is frequently used to take a particular
+action based on the presence or absense of a particular environment
+variable or request header. This can be done more efficiently using the
+<If>.RewriteRule is used to enforce a canonical
+hostname, such as www.example.com instead of
+example.com. This can be done using the <If> direct, as shown here:
+<If "$req{Host} = 'example.com'">
+RedirectMatch (.*) http://www.example.com$1
+</If>
+mod_rewrite in many common scenarios.RedirectMatch
+allows you to include a regular expression in your redirection criteria,
+providing many of the benefits of using RewriteRule.RewriteRule is to redirect an entire
+class of URLs. For example, all URLs in the /one directory
+must be redirected to http://one.example.com/, or perhaps
+all http requests must be redirected to
+https.Redirect
+directive. Remember that Redirect preserves path
+information. That is to say, a redirect for a URL /one will
+also redirect all URLs under that, such as /one/two.html
+and /one/three/four.html./one to
+http://one.example.com, do the following:http URLs to https, do the
+following:
+Redirect / https://www.example.com/
+</VirtualHost >
+
+<VirtualHost *:443>
+ServerName www.example.com
+
+# ... SSL configuration goes here
+</VirtualHost >
+RewriteRule to perform this task may be
+appropriate if there are other RewriteRule directives in
+the same scope. This is because, when there are Redirect
+and RewriteRule directives in the same scope, the
+RewriteRule directives will run first, regardless of the
+order of appearance in the configuration file.RewriteRule would be appropriate if you don't have access
+to the main server configuration file, and are obliged to perform this
+task in a .htaccess file instead.mod_rewrite,
+Alias is the preferred method, for reasons of simplicity
+and performance.mod_rewrite to perform this mapping may be
+appropriate when you do not have access to the server configuration
+files. Alias may only be used in server or virtualhost context, and not
+in a .htaccess file.
+Options FollowSymLinks enabled on your
+server..htaccess files.RewriteRule provides the [P] flag to pass rewritten URIs through
+RewriteRule instead when there are
+other RewriteRules in effect in the same scope, as a
+RewriteRule will usually take effect before a
+ProxyPass, and so may preempt what you're trying to
+accomplish.www.example.com instead of
+example.com. This can be done using the
+RedirectMatch (.*) http://www.example.com$1
+</If>
+
RewriteRule Flags
+
+
+RewriteRule directive,
+providing detailed explanations and examples.
Introduction
B (escape backreferences)
C|chain
CO|cookie
DPI|discardpathinfo
E|env
F|forbidden
G|gone
H|handler
L|last
N|next
NC|nocase
NE|noescape
NS|nosubreq
P|proxy
PT|passthrough
QSA|qsappend
QSD|qsdiscard
R|redirect
S|skip
T|typeSee also
Introduction
+RewriteRule can have
+its behavior modified by one or more flags. Flags are included in
+square brackets at the end of the rule, and multiple flags are separated
+by commas.
+RewriteRule pattern target [Flag1,Flag2,Flag3]
+CO, as well as
+a longer form, such as cookie. Some flags take one or more
+arguments. Flags are not case sensitive.B (escape backreferences)
+RewriteRule to escape non-alphanumeric
+characters before applying the transformation.
+mod_rewrite has to unescape URLs before mapping them,
+so backreferences will be unescaped at the time they are applied.
+Using the B flag, non-alphanumeric characters in backreferences
+will be escaped. For example, consider the rule:
+RewriteRule ^(/.*)$ /index.php?show=$1
+/C++ to
+/index.php?show=/C++. But it will also map
+/C%2b%2b to /index.php?show=/C++, because
+the %2b has been unescaped. With the B flag, it will
+instead map to /index.php?show=/C%2b%2b.C|chain
+RewriteRule is chained to the next
+rule. That is, if the rule matches, then it is processed as usual and
+control moves on to the next rule. However, if it does not match, then
+the next rule, and any other rules that are chained together, will be
+skipped.CO|cookie
+RewriteRule
+matches. The argument consists of three required fields and five optional
+fields.
+[CO=NAME:VALUE:domain:lifetime:path:secure:httponly]
+
+
+
+www.example.com, or it may be a domain,
+such as .example.com. It must be at least two parts
+separated by a dot. That is, it may not be merely .com or
+.net. Cookies of that kind are forbidden by the cookie
+security model./customers/ or /files/download/./ - that is, the entire
+website.secure, true, or 1,
+the cookie will only be permitted to be translated via secure (https)
+connections.HttpOnly, true, or
+1, the cookie will have the HttpOnly flag set,
+which means that the cookie will be inaccessible to JavaScript code on
+browsers that support this feature.
+RewriteEngine On
+RewriteRule ^/index\.html - [CO=frontdoor:yes:.example.com:1440:/]
+.example.com domain. It will be set to expire in 1440
+minutes (24 hours) and will be returned for all URIs.DPI|discardpathinfo
+RewriteRule
+compares against is the concatenation of the current values of the URI
+and PATH_INFO.RewriteRule directives, without regard for
+which parts of the URI came from the current PATH_INFO, the final
+URI may have multiple copies of PATH_INFO appended to it.E|env
+
+[E=VAR:VAL]
+[E=!VAR]
+VAL may contain backreferences ($N or
+%N) which will be expanded.
+[E=VAR]
+VAR to an
+empty value.
+[E=!VAR]
+VAR.
+RewriteRule \.(png|gif|jpg) - [E=image:1]
+CustomLog logs/access_log combined env=!image
+SetEnvIf. This technique is offered as
+an example, not as a recommendation.F|forbidden
+Deny directive, this
+allows more flexibility in assigning a Forbidden status..exe files from being
+downloaded from your server.
+RewriteRule \.exe - [F]
+G|gone
+
+RewriteRule oldproduct - [G,NC]
+H|handler
+
+RewriteRule !\. - [H=application/x-httpd-php]
+!\. - will match any request
+that does not contain the literal . character.
+.php files to be displayed by mod_php
+if they are requested with the .phps extension:
+RewriteRule ^(/source/.+\.php)s$ $1 [H=application/x-httpd-php-source]
+^(/source/.+\.php)s$ - will
+match any request that starts with /source/ followed by 1 or
+n characters followed by .phps literally. The backreference
+$1 referrers to the captured match within parenthesis of the regular
+expression.L|last
+mod_rewrite to stop processing
+the rule set. In most contexts, this means that if the rule matches, no
+further rules will be processed. This corresponds to the
+last command in Perl, or the break command in
+C. Use this flag to indicate that the current rule should be applied
+immediately without considering further rules.RewriteRule in either
+.htaccess files or in
+<Directory> sections,
+it is important to have some understanding of how the rules are
+processed. The simplified form of this is that once the rules have been
+processed, the rewritten request is handed back to the URL parsing
+engine to do what it may with it. It is possible that as the rewritten
+request is handled, the .htaccess file or
+<Directory> section
+may be encountered again, and thus the ruleset may be run again from the
+start. Most commonly this will happen if one of the rules causes a
+redirect - either internal or external - causing the request process to
+start over.RewriteRule directives in one of these
+contexts, that you take explicit steps to avoid rules looping, and not
+count solely on the [L] flag to terminate execution of a series of
+rules, as shown below.index.php, giving the original request as a query string
+argument to index.php, however, the RewriteCond ensures that if the request
+is already for index.php, the RewriteRule will be skipped.
+RewriteBase /
+RewriteCond %{REQUEST_URI} !=/index.php
+RewriteRule ^(.*) /index.php?req=$1 [L,PT]
+N|next
+
+RewriteRule (.*)A(.*) $1B$2 [N]
+while loop: While this
+pattern still matches (i.e., while the URI still contains an
+A), perform this substitution (i.e., replace the
+A with a B).NC|nocase
+RewriteRule to be matched in a
+case-insensitive manner. That is, it doesn't care whether letters appear
+as upper-case or lower-case in the matched URI..jpg and .JPG files are both acceptable, for
+example.
+RewriteRule (.*\.(jpg|gif|png))$ http://images.example.com$1 [P,NC]
+NE|noescape
+& and
+?, for example, will be converted to their hexcode
+equivalent. Using the [NE] flag prevents that from happening.
+
+RewriteRule ^/anchor/(.+) /bigpage.html#$1 [NE,R]
+/anchor/xyz to
+/bigpage.html#xyz. Omitting the [NE] will result in the #
+being converted to its hexcode equivalent, %23, which will
+then result in a 404 Not Found error condition.
+NS|nosubreq
+mod_dir
+tries to find out information about possible directory default files
+(such as index.html files), this is an internal
+subrequest, and you often want to avoid rewrites on such subrequests.
+On subrequests, it is not always useful, and can even cause errors, if
+the complete set of rules are applied. Use this flag to exclude
+problematic rules.P|proxy
+mod_proxy, and handled via a proxy request. For
+example, if you wanted all image requests to be handled by a back-end
+image server, you might do something like the following:
+RewriteRule (.*)\.(jpg|gif|png) http://images.example.com$1.$2 [P]
+http://hostname) which can be
+handled by the mod_proxy. If not, you will get an
+error from the proxy module. Use this flag to achieve a
+more powerful implementation of the ProxyPass directive,
+to map remote content into the namespace of the local server.mod_proxy must be enabled in order
+to use this flag.PT|passthrough
+
+RewriteRule to be passed back through
+URL mapping, so that location-based mappings, such as Alias, Redirect, or ScriptAlias, for example, might have a
+chance to take effect.
+Alias
+for /icons, and have a RewriteRule pointing there, you should
+use the [PT] flag to ensure that the
+Alias is evaluated.
+
+Alias /icons /usr/local/apache/icons
+RewriteRule /pics/(.+)\.jpg /icons/$1.gif [PT]
+PT flag implies the L flag:
+rewriting will be stopped in order to pass the request to
+the next phase of processing.PT flag is implied in per-directory
+contexts such as
+<Directory> sections
+or in .htaccess files. The only way to circumvent that
+is to rewrite to -.QSA|qsappend
+RewriteRule is to discard
+the existing query string, and replace it with the newly generated one.
+Using the [QSA] flag causes the query strings to be combined.
+
+RewriteRule /pages/(.+) /page.php?page=$1 [QSA]
+/pages/123?one=two will be
+mapped to /page.php?page=123&one=two. Without the [QSA]
+flag, that same request will be mapped to
+/page.php?page=123 - that is, the existing query string
+will be discarded.
+QSD|qsdiscard
+RewriteRule is to copy that query
+string to the target URI. Using the [QSD] flag causes the query string
+to be discarded.
+RewriteRule target
+URI.
+R|redirect
+http://servername/) then a redirect will be issued to that
+location. Otherwise, the current protocol, servername, and port number
+will be used to generate the URL sent with the redirect.
+L were used.temp (default),
+permanent, or seeother.http://thishost[:thisport] to the URI, but then passes this
+on to the next rule in the ruleset, which can often result in 'Invalid
+URI in request' warnings.
+S|skip
+goto statement in your rewrite
+ruleset. In the following example, we only want to run the RewriteRule if the requested URI
+doesn't correspond with an actual file.
+# Is the request for a non-existent file?
+RewriteCond %{REQUEST_FILENAME} !-f
+RewriteCond %{REQUEST_FILENAME} !-d
+# If so, skip these two RewriteRules
+RewriteRule .? - [S=2]
+
+RewriteRule (.*\.gif) images.php?$1
+RewriteRule (.*\.html) docs.php?$1
+RewriteCond only applies to the
+RewriteRule immediately
+following it. Thus, if you want to make a RewriteCond apply
+to several RewriteRules, one possible technique is to
+negate those conditions and use a [Skip] flag. So, you can
+use this to make pseudo if-then-else constructs: The last rule of
+the then-clause becomes skip=N, where N is the
+number of rules in the else-clause.T|type
+AddType directive.
+# Serve .pl files as plain text
+RewriteRule \.pl$ - [T=text/plain]
+
+# Files with 'IMG' in the name are jpg images.
+RewriteRule IMG - [T=image/jpg]
+<FilesMatch>
+instead. Always consider the alternate
+solutions to a problem before resorting to rewrite, which will
+invariably be a less efficient solution than the alternatives.- (dash)
+as the substitution for the entire round of mod_rewrite processing,
+otherwise the MIME-type set with this flag is lost due to an internal
+re-processing (including subsequent rounds of mod_rewrite processing).
+The L flag can be useful in this context to end the
+current round of mod_rewrite processing.
Les drapeaux de réécriture
+
+
+RewriteRule, en fournissant
+des explications détaillées et des exemples.
Introduction
B (échappement dans les références arrières)
C|chain
CO|cookie
DPI|discardpathinfo
E|env
F|forbidden
G|gone
H|handler
L|last
N|next
NC|nocase
NE|noescape
NS|nosubreq
P|proxy
PT|passthrough
QSA|qsappend
QSD|qsdiscard
R|redirect
S|skip
T|typeVoir aussi
Introduction
+RewriteRule peut être modifié par un ou
+plusieurs drapeaux. Les drapeaux sont situés en fin de règle, entourés
+de crochets, et séparés le cas échéant par des virgules.
+RewriteRule modèle cible [drapeau1,drapeau2,drapeau3]
+CO, ainsi
+qu'une forme longue, comme cookie. Certains drapeaux
+peuvent avoir un ou plusieurs arguments. Les drapeaux sont insensibles à
+la casse.B (échappement dans les références arrières)
+RewriteRule échappe les caractères
+non-alphanumériques avant d'appliquer la transformation.mod_rewrite doit supprimer les séquences d'échappement
+des URLs avant leur
+mise en correspondance avec le système de fichiers ; les séquences
+d'échappement sont donc supprimées des références arrières au moment où
+ces dernières sont appliquées. Avec le drapeau B, les caractères
+non-alphanumériques des références arrières seront échappés. Considérons
+par exemple cette règle :
+RewriteRule ^(/.*)$ /index.php?show=$1
+/C++ sera réécrit en
+/index.php?show=/C++. Mais /C%2b%2b sera lui
+aussi réécrit en /index.php?show=/C++, car le caractère
+%2b aura été "déséchappé". Avec le drapeau B par contre,
+/C%2b%2b sera réécrit en
+/index.php?show=/C%2b%2b.C|chain
+RewriteRule est chaînée avec la
+suivante. Autrement dit, si la règle s'applique, elle est traitée
+normalement et passe le contrôle à la règle suivante. Par contre, si
+elle ne s'applique pas, la règle suivante, ainsi que toutes les règles
+chaînées qui suivent, seront sautées.CO|cookie
+RewriteRule
+s'applique. Il possède trois arguments obligatoires et
+cinq arguments optionnels.
+[CO=NAME:VALUE:domain:lifetime:path:secure:httponly]
+
+
+
+www.example.com, ou un
+domaine, comme .example.com. Il doit comporter au moins
+deux parties séparées par un point. C'est à dire que vous ne pouvez pas
+utiliser les valeurs .com ou .net. En effet,
+ce style de cookie est interdit par le modèle de sécurité des cookies./clients/ or
+/fichiers/telechargement/./ - c'est à dire l'ensemble du
+site web.secure,
+true, ou 1, le cookie ne pourra être transmis
+que dans le cadre d'une connexion sécurisée (https).HttpOnly,
+true, ou 1, le cookie aura son drapeau
+HttpOnly activé, ce qui signifie qu'il sera inaccessible au
+code JavaScript pour les navigateurs qui supportent cette
+fonctionnalité.
+RewriteEngine On
+RewriteRule ^/index\.html - [CO=frontdoor:yes:.example.org:1440:/]
+.example.org. Sa
+durée de vie est limitée à 1440 minutes (24 heures), et il sera renvoyé
+pour tous les URIs.DPI|discardpathinfo
+RewriteRule est la concaténation des
+valeurs courantes de l'URI et de PATH_INFO.RewriteRule, sans prendre en compte
+quelles parties de l'URI provenaient du PATH_INFO courant, l'URI final
+pourra se voir ajouter plusieurs copies de PATH_INFO.E|env
+
+[E=!VAR]
+VAL peut comporter des références arrières
+($N ou %N) qui seront développées.
+[E=VAR]
+VAR avec une valeur vide.
+[E=!VAR]
+VAR.
+RewriteRule \.(png|gif|jpg) - [E=image:1]
+CustomLog logs/access_log combined env=!image
+SetEnvIf. Cette technique
+est présentée à titre d'exemple et non de recommandation.F|forbidden
+Deny,
+mais ce drapeau offre plus de souplesse dans l'attribution d'un statut
+Forbidden..exe depuis votre serveur.
+RewriteRule \.exe - [F]
+G|gone
+
+RewriteRule ancienne-ressource - [G,NC]
+H|handler
+
+RewriteRule !\. - [H=application/x-httpd-php]
+!\. - correspond à
+toute requête qui ne contient pas le caractère ..
+.php soient
+affichés par mod_php dans le cas où ils font
+l'objet d'une requête avec l'extension .phps :
+RewriteRule ^(/source/.+\.php)s$ $1 [H=application/x-httpd-php-source]
+^(/source/.+\.php)s$ - va correspondre à toute requête qui
+débutera par /source/, continuera par 1 ou n caractères
+puis par .phps. La référence arrière $1 fait référence à la
+correspondance capturée entre parenthèses de l'expression
+rationnelle.L|last
+mod_rewrite
+arrête le traitement du jeu de règles. Cela signifie dans la plupart des
+situations que si la règle s'applique, aucune autre règle ne sera
+traitée. Ce drapeau correspond à la commande Perl last, ou
+à la commande break en C. Utilisez ce drapeau pour indiquer
+que la règle courante doit être appliquée immédiatement, sans tenir
+compte des règles ultérieures.RewriteRule dans des fichiers
+.htaccess ou des sections <Directory>, il est important d'avoir quelques
+notions sur la manière dont les règles sont traitées. Pour simplifier,
+une fois les règles traitées, la requête réécrite est passée à nouveau
+au moteur d'interprétation des URLs afin que ce dernier puisse la
+traiter. Il est possible qu'au cours du traitement de la requête
+réécrite, le fichier .htaccess ou la section <Directory> soient à nouveau
+rencontrés, entraînant un nouveau traitement du jeu de règles depuis le
+début. Cette situation se présente le plus souvent lorsqu'une des règles
+provoque une redirection - interne ou externe - ce qui réinitialise le
+traitement de la requête.RewriteRule dans un de ces contextes,
+il importe par conséquent de prévoir explicitement des étapes permettant
+d'éviter un bouclage infini sur les règles,
+et de ne pas compter seulement sur
+le drapeau [L] pour terminer l'exécution d'une série de règles, comme
+décrit ci-dessous.index.php, la requête originale étant ajoutée comme chaîne
+de requête en argument à index.php ; cependant, la
+directive RewriteCond permet de s'assurer que si
+la requête concerne déjà index.php, la directive RewriteRule sera sautée.
+RewriteBase /
+RewriteCond %{REQUEST_URI} !=/index.php
+RewriteRule ^(.*) /index.php?req=$1 [L,PT]
+N|next
+
+RewriteRule (.*)A(.*) $1B$2 [N]
+while : tant que le modèle de la règle correspond (c'est à
+dire, tant que l'URI contient un A),
+effectuer la substitution (c'est à dire, remplacer le A par
+un B).NC|nocase
+RewriteRule est comparé à la requête de
+manière insensible à la casse. C'est à dire que cette comparaison
+s'effectue sans tenir compte des majuscules/minuscules dans l'URI
+comparé..jpg aussi
+bien que .JPG seront acceptés.
+RewriteRule (.*\.(jpg|gif|png))$ http://images.example.com$1 [P,NC]
+NE|noescape
+& et
+?, sont convertis en leur équivalent
+hexadécimal. Le drapeau [NE] permet d'éviter cette conversion.
+
+RewriteRule ^/ancre/(.+) /grosse-page.html#$1 [NE,R]
+/anchor/xyz est réécrit en
+/bigpage.html#xyz. En l'absence du drapeau [NE], le #
+aurait été converti en son équivalent hexadécimal, %23, ce
+qui aurait provoqué un code d'erreur "404 Not Found".
+NS|nosubreq
+mod_dir recherche des informations à propos des
+fichiers par défaut du répertoire (comme les fichiers
+index.html), il s'agit d'une sous-requête interne, et vous
+ne désirez en général pas que ces sous-requêtes soient réécrites. Cette
+réécriture
+n'est pas toujours utile pour les sous-requêtes, et peut même causer des
+erreurs si l'ensemble du jeu de règles est appliqué. L'utilisation de
+ce drapeau permet d'exclure les règles qui peuvent poser problème.P|proxy
+mod_proxy, et ceci via une requête de
+mandataire. Par exemple, si vous voulez que toutes les requêtes d'images
+soient traitées par un serveur d'images annexe, vous pouvez utiliser
+une règle de ce style :
+RewriteRule (.*)\.(jpg|gif|png) http://images.example.com$1.$2 [P]
+http://nom-serveur)
+qui puisse être traitée par le module mod_proxy. Dans
+le cas contraire, le module mandataire vous renverra une erreur.
+L'utilisation de ce drapeau implémente de manière plus puissante la
+directive ProxyPass, pour
+faire correspondre le contenu distant à l'espace de nommage du serveur
+local.mod_proxy doit être activé pour pouvoir
+utiliser ce drapeau.PT|passthrough
+
+RewriteRule est passé à nouveau au
+système de mise en correspondance des URLs avec le système de fichiers,
+de façon à ce que les systèmes de mise en correspondance basés sur les
+chemins de fichiers, comme la directive Alias, Redirect, ou ScriptAlias, par exemple, puissent avoir une
+chance d'accomplir leur tâche.
+Alias pour /icons, et une règle RewriteRule qui renvoie vers /icons,
+vous devez utiliser le drapeau [PT] pour être sûr que l'Alias sera bien évalué.
+
+Alias /icons /usr/local/apache/icons
+RewriteRule /pics/(.+)\.jpg /icons/$1.gif [PT]
+PT, le drapeau L est
+implicite : la réécriture s'arrêtera afin de transmettre la requête à la
+phase suivante du traitement.PT est implicite dans des contextes
+de répertoire comme les sections <Directory> ou les fichiers
+.htaccess. Le seul moyen de contourner ceci consiste à
+réécrire vers -.QSA|qsappend
+RewriteRule est de supprimer la
+query string (il s'agit des paramètres éventuellement passés dans l'URL après le
+caractère ?, usuellement pour les formulaires traités par la
+méthode HTTP GET) existante, et de la remplacer par celle nouvellement créée.
+Avec le drapeau [QSA], les chaînes de requête peuvent être combinées.
+
+RewriteRule /pages/(.+) /page.php?page=$1 [QSA]
+/pages/123?one=two sera réécrite en
+/page.php?page=123&one=two. Sans le drapeau [QSA], la
+même requête sera réécrite en /page.php?page=123 -
+autrement dit, la chaîne de requête (query string) existante sera supprimée.
+QSD|qsdiscard
+RewriteRule consiste à copier cette
+chaîne de paramètres dans l'URI cible. Avec le drapeau [QSD], la chaîne
+de paramètres est supprimée.
+R|redirect
+http://nom-du-serveur/),
+ une redirection sera effectuée vers cette adresse. Dans le cas contraire,
+ le protocole courant, le nom du serveur et le numéro de port seront
+ utilisés pour générer l'URL envoyée avec la redirection.
+L
+était utilisé.temp (défaut), permanent, ou
+seeother.http://cet-hôte[:ce-port], mais passe ensuite cette adresse
+à la règle suivante, ce qui provoquera le plus souvent des
+avertissements 'Invalid URI in request'.
+S|skip
+goto dans votre jeu de règles de réécriture. Dans
+l'exemple suivant, nous ne voulons exécuter la règle RewriteRule que si l'URI demandé ne
+correspond pas à un fichier existant.
+# La requête concerne-t-elle un fichier qui n'existe pas ?
+RewriteCond %{REQUEST_FILENAME} !-f
+RewriteCond %{REQUEST_FILENAME} !-d
+# Si c'est la cas, on saute les deux règles de réécriture suivantes
+RewriteRule .? - [S=2]
+
+RewriteRule (.*\.gif) images.php?$1
+RewriteRule (.*\.html) docs.php?$1
+RewriteCond ne s'applique
+qu'à la règle qui la suit immédiatement. Ainsi, si vous voulez
+qu'une directive RewriteCond s'applique à plusieurs règles
+RewriteRule, une technique possible consiste à inverser ces
+conditions et à utiliser le drapeau [Skip]. Cette technique permet
+d'élaborer des pseudo-constructions if-then-else : la dernière règle du
+bloc then contiendra skip=N, où N est le nombre de règles
+contenues dans le bloc else.T|type
+AddType.
+# Sert les fichier .pl en tant que plein texte
+RewriteRule \.pl$ - [T=text/plain]
+
+# Les fichiers dont le nom contient 'IMG' sont des images jpg.
+RewriteRule IMG - [T=image/jpg]
+<FilesMatch>. Il faut toujours
+envisager la possibilité d'une solution alternative à un problème avant
+d'avoir recours à la réécriture, qui sera toujours moins efficace qu'une
+solution alternative.-
+(tiret) comme substitution, dans toute la séquence de réécriture de
+mod_rewrite, sinon le type MIME défini avec ce drapeau
+sera perdu suite à un retraitement interne (y compris les séquences de
+réécriture suivantes de mod_rewrite). Dans ce contexte, vous pouvez
+utiliser le drapeau L pour terminer la séquence
+courante de réécriture de mod_rewrite.
A
cookie. Some flags take one or more
arguments. Flags are not case sensitive.
-Each flag has a long and short form. While it is most common to use +
Each flag (with a few exceptions) +has a long and short form. While it is most common to use the short form, it is recommended that you familiarize yourself with the long form, so that you remember what each flag is supposed to do.
+Flags that alter metadata associated with the request (T=, H=, E=) +have no affect in per-directory and htaccess context, when a substitution +(other than '-') is performed during the same round of rewrite processing. +
+Presented here are each of the available flags, along with an example of how you might use them.
+The [B] flag instructs
mod_rewrite has to unescape URLs before mapping them,
+so backreferences will be unescaped at the time they are applied.
+Using the B flag, non-alphanumeric characters in backreferences
+will be escaped. For example, consider the rule:
This will map /C++ to
+/index.php?show=/C++. But it will also map
+/C%2b%2b to /index.php?show=/C++, because
+the %2b has been unescaped. With the B flag, it will
+instead map to /index.php?show=/C%2b%2b.
This escaping is particularly necessary in a proxy situation, +when the backend may break if presented with an unescaped URL.
+ +The [C] or [chain] flag indicates that the The [CO], or [cookie] flag, allows you to set a cookie when a
particular You must declare a name and value for the cookie to be set, and the
-domain for which you wish the cookie to be valid. You may optionally set
-the lifetime of the cookie, and the path for which it should be
-returned. By default, the lifetime of the cookie is the current browser
-session. By default, the path for which the cookie will be valid is "/" - that
-is, the entire website. The full syntax for the flag, including all attributes, is as
+follows: You must declare a name and value for the cookie to be set. You may optionally also set the following values: Several examples are offered here: This rule doesn't rewrite the request (the "-" rewrite target tells
-mod_rewrite to pass the request through unchanged) but sets a cookie
+ In the example give, the rule doesn't rewrite the request.
+The "-" rewrite target tells mod_rewrite to pass the request
+through unchanged. Instead, it sets a cookie
called 'frontdoor' to a value of 'yes'. The cookie is valid for any host
-in the The DPI flag causes the PATH_INFO portion of the rewritten URI to be
+discarded. This flag is available in version 2.2.12 and later. In per-directory context, the URI each The current URI can be the initial URI as requested by the client, the
+result of a previous round of mod_rewrite processing, or the result of
+a prior rule in the current round of mod_rewrite processing. In contrast, the PATH_INFO that is appended to the URI before each
+rule reflects only the value of PATH_INFO before this round of
+mod_rewrite processing. As a consequence, if large portions
+of the URI are matched and copied into a substitution in multiple
+ Use this flag on any substitution where the PATH_INFO that resulted
+from the previous mapping of this request to the filesystem is not of
+interest. This flag permanently forgets the PATH_INFO established
+before this round of mod_rewrite processing began. PATH_INFO will
+not be recalculated until the current round of mod_rewrite processing
+completes. Subsequent rules during this round of processing will see
+only the direct result of substitutions, without any PATH_INFO
+appended. With the [E], or [env] flag, you can set the value of an environment
variable. Note that some environment variables may be set after the rule
@@ -156,7 +256,7 @@ an example, not as a recommendation. Using the [F] flag causes Apache to return a 403 Forbidden status
+ Using the [F] flag causes the server to return a 403 Forbidden status
code to the client. While the same behavior can be accomplished using
the
+
+
www.example.com, or it may be a domain,
+such as .example.com. It must be at least two parts
+separated by a dot. That is, it may not be merely .com or
+.net. Cookies of that kind are forbidden by the cookie
+security model./customers/ or /files/download/./ - that is, the entire
+website.secure, true, or 1,
+the cookie will only be permitted to be translated via secure (https)
+connections.HttpOnly, true, or
+1, the cookie will have the HttpOnly flag set,
+which means that the cookie will be inaccessible to JavaScript code on
+browsers that support this feature.
-RewriteRule ^/index.html - [CO=frontdoor:yes:.apache.org:1440:/]
+RewriteRule ^/index\.html - [CO=frontdoor:yes:.example.com:1440:/]
.apache.org domain. It will be set to expire in 1440
+in the .example.com domain. It will be set to expire in 1440
minutes (24 hours) and will be returned for all URIs.
When using [F], an [L] is implied - that is, the response is returned +immediately, and no further rules are evaluated.
+The [G] flag forces Apache to return a 410 Gone status with the +
The [G] flag forces the server to return a 410 Gone status with the response. This indicates that a resource used to be available, but is no longer available.
@@ -185,6 +288,10 @@ rewrite target when using the [G] flag:When using [F], an [L] is implied - that is, the response is returned +immediately, and no further rules are evaluated.
+!\. - will match any request
that does not contain the literal . character.
+
+This can be also used to force the handler based on some conditions.
+For example, the following snippet used in per-server context allows
+.php files to be displayed by mod_php
+if they are requested with the .phps extension:
The regular expression above - ^(/source/.+\.php)s$ - will
+match any request that starts with /source/ followed by 1 or
+n characters followed by .phps literally. The backreference
+$1 referrers to the captured match within parenthesis of the regular
+expression.
The [L] flag causes
last command in Perl, or the break command in
+C. Use this flag to indicate that the current rule should be applied
+immediately without considering further rules.
If you are using
It is therefore important, if you are using
An alternative flag, [END], can be used to terminate not only the +current round of rewrite processing but prevent any subsequent +rewrite processing from occuring in per-directory (htaccess) +context. This does not apply to new requests resulting from external +redirects.
+The example given here will rewrite any request to
index.php, giving the original request as a query string
-argument to index.php, however, if the request is already
-for index.php, this rule will be skipped.
index.php, however, the index.php, the -The [N] flag causes the ruleset to start over again from the top. Use +The [N] flag causes the ruleset to start over again from the top, using +the result of the ruleset so far as a starting point. Use with extreme caution, as it may result in loop.
@@ -256,7 +391,9 @@ RewriteRule (.*)A(.*) $1B$2 [N]
You can think of this as a while loop: While this
-pattern still matches, perform this substitution.
A), perform this substitution (i.e., replace the
+A with a B).
Use of the [NS] flag prevents the rule from being used on subrequests. For example, a page which is included using an SSI (Server Side Include) is a subrequest, and you may want to avoid rewrites -happening on those subrequests.
+happening on those subrequests. Also, whenindex.html files), this is an internal
+subrequest, and you often want to avoid rewrites on such subrequests.
+On subrequests, it is not always useful, and can even cause errors, if
+the complete set of rules are applied. Use this flag to exclude
+problematic rules.
+
+To decide whether or not to use this rule: if you prefix URLs with +CGI-scripts, to force them to be processed by the CGI-script, it's +likely that you will run into problems (or significant overhead) +on sub-requests. In these cases, use this flag.
Images, javascript files, or css files, loaded as part of an HTML page, @@ -318,10 +466,22 @@ image server, you might do something like the following:
RewriteRule (.*)\.(jpg|gif|png) http://images.example.com$1.$2 [P] -Use of the [P] flag implies [L] - that is, the request is immediatly +
Use of the [P] flag implies [L] - that is, the request is immediately pushed through the proxy, and any following rules will not be considered.
+
+You must make sure that the substitution string is a valid URI
+(typically starting with http://hostname) which can be
+handled by the
Note:
@@ -356,6 +518,16 @@ Omission of the [PT] flag in this case will cause the Alias to be ignored, resulting in a 'File not found' error being returned.
+The PT flag implies the L flag:
+rewriting will be stopped in order to pass the request to
+the next phase of processing.
Note that the PT flag is implied in per-directory
+contexts such as
+.htaccess files. The only way to circumvent that
+is to rewrite to -.
http://servername/) then a redirect will be issued to that
-location. Otherwise, the current servername will be used to generate the
-URL sent with the redirect.
+location. Otherwise, the current protocol, servername, and port number
+will be used to generate the URL sent with the redirect.
-A status code may be specified, in the range 300-399, with a 302 status -code being used by default if none is specified. +Any valid HTTP response status code may be specified, +using the syntax [R=305], with a 302 status code being used by +default if none is specified. The status code specified need not +necessarily be a redirect (3xx) status code.
+If a status code is outside the redirect range (300-399) then the
+substitution string is dropped entirely, and rewriting is stopped as if
+the L were used.
In addition to response status codes, you may also specify redirect
+status using their symbolic names: temp (default),
+permanent, or seeother.
You will almost always want to use [R] in conjunction with [L] (that is,
use [R,L]) because on its own, the [R] flag prepends
@@ -427,8 +609,10 @@ module="mod_rewrite">RewriteCond only applies to the
RewriteCond apply
to several RewriteRules, one possible technique is to
-negate those conditions and use a [Skip] flag.
skip=N, where N is the
+number of rules in the else-clause.
If used in per-directory context, use only - (dash)
-as the substitution for the entire round of mod_rewrite processing,
-otherwise the MIME-type set with this flag is lost due to an internal
+as the substitution for the entire round of mod_rewrite processing,
+otherwise the MIME-type set with this flag is lost due to an internal
re-processing (including subsequent rounds of mod_rewrite processing).
-The L flag can be useful in this context to end the
+The L flag can be useful in this context to end the
current round of mod_rewrite processing.
Ce document décrit les drapeaux disponibles dans la directive
+
Le comportement d'une directive
Les drapeaux ont tous une forme courte, comme CO, ainsi
+qu'une forme longue, comme cookie. Certains drapeaux
+peuvent avoir un ou plusieurs arguments. Les drapeaux sont insensibles à
+la casse.
Chaque drapeau (à quelques exceptions près) possède une forme longue et une forme courte. Bien que +la forme courte soit la plus couramment utilisée, nous vous recommandons +de vous familiariser avec les drapeaux sous leur forme longue, afin de +bien mémoriser ce que chaque drapeau est supposé faire.
+ +Les drapeaux qui modifient les métadonnées associées à la requête +(T=, H=, E=) n'ont aucun effet dans un contexte de répertoire ou de +fichier htaccess, lorsqu'une substitution (autre que '-') est effectuée +au cours de la même passe du processus de réécriture. +
+ +Chaque drapeau disponible est présenté ici, avec un exemple +d'utilisation.
+Avec le drapeau [B], la directive
mod_rewrite doit supprimer les séquences d'échappement
+des URLs avant leur
+mise en correspondance avec le système de fichiers ; les séquences
+d'échappement sont donc supprimées des références arrières au moment où
+ces dernières sont appliquées. Avec le drapeau B, les caractères
+non-alphanumériques des références arrières seront échappés. Considérons
+par exemple cette règle :
Avec cet exemple, /C++ sera réécrit en
+/index.php?show=/C++. Mais /C%2b%2b sera lui
+aussi réécrit en /index.php?show=/C++, car le caractère
+%2b aura été "déséchappé". Avec le drapeau B par contre,
+/C%2b%2b sera réécrit en
+/index.php?show=/C%2b%2b.
Ce processus d'échappement est en particulier nécessaire dans le +contexte d'un mandataire, où l'accès au serveur d'arrière-plan échouera +si on présente à ce dernier une URL non échappée.
+ +Le drapeau [C] ou [chain] indique que la règle
Le drapeau [CO], ou [cookie], vous permet de définir un cookie
+lorsqu'une règle
La syntaxe complète de ce drapeau, avec tous ses attributs, est la +suivante :
+ +Vous devez déclarer un nom et une valeur pour que le cookie puisse +être défini.
+ +Vous pouvez aussi définir les valeurs suivantes :
+ +www.example.com, ou un
+domaine, comme .example.com. Il doit comporter au moins
+deux parties séparées par un point. C'est à dire que vous ne pouvez pas
+utiliser les valeurs .com ou .net. En effet,
+ce style de cookie est interdit par le modèle de sécurité des cookies./clients/ or
+/fichiers/telechargement/./ - c'est à dire l'ensemble du
+site web.secure,
+true, ou 1, le cookie ne pourra être transmis
+que dans le cadre d'une connexion sécurisée (https).HttpOnly,
+true, ou 1, le cookie aura son drapeau
+HttpOnly activé, ce qui signifie qu'il sera inaccessible au
+code JavaScript pour les navigateurs qui supportent cette
+fonctionnalité.Voici un exemple :
+ +Dans l'exemple ci-dessus, la règle ne réécrit
+pas la requête. La cible de réécriture "-"
+indique à mod_rewrite de transmettre la requête sans
+modification. Par contre, il
+définit un cookie nommé 'frontdoor' avec une valeur 'yes'. Le cookie est
+valide pour tout hôte situé dans le domaine .example.org. Sa
+durée de vie est limitée à 1440 minutes (24 heures), et il sera renvoyé
+pour tous les URIs.
Avec le drapeau DPI, la partie PATH_INFO de l'URI +réécrit est supprimée.
+Ce drapeau est disponible dans les versions 2.2.12 et supérieures.
+Dans un contexte de répertoire, l'URI mis en comparaison par chaque
+règle
L'URI courant peut être l'URI initial tel qu'il a été fourni par le +client, le résultat d'une passe précédente du processus de réécriture, +ou le résultat de la règle précédente dans le processus courant de +réécriture.
+ +Par contre, la partie PATH_INFO ajoutée à l'URI avant chaque règle ne
+reflète que la valeur de PATH_INFO avant la passe courante du processus
+de réécriture. En conséquence, si de larges portions de l'URI
+correspondent et sont traduites via plusieurs directives
+
Utilisez ce drapeau pour toute substitution où la présence du PATH_INFO qui +résultait de la mise en correspondance précédente de cette requête avec +le système de fichier n'est pas nécessaire. Avec ce drapeau, le +PATH_INFO établi avant que cette passe du processus de réécriture ne +débute est oublié. PATH_INFO ne sera pas recalculé tant que la passe +courante du processus de réécriture ne sera pas achevée. Les règles +suivantes de cette passe ne verront que le résultat direct des +substitutions, sans aucun PATH_INFO ajouté.
+Avec le drapeau [E], ou [env], vous pouvez définir la valeur d'une +variable d'environnement. Notez que certaines variables d'environnement +peuvent être définies après le traitement de la règle, annulant par +la-même ce que vous avez défini. Voir le document +sur les variables d'environnement pour plus de détails sur le +fonctionnement des variables d'environnement.
+ +La syntaxe complète pour ce drapeau est :
+ +VAL peut comporter des références arrières
+($N ou %N) qui seront développées.
En utilisant la version courte
+ +vous pouvez définir la variable d'environnement nommée
+VAR avec une valeur vide.
La forme
+ +permet d'annuler la définition de la variable VAR.
Les variables d'environnement s'emploient dans différents contextes, +comme les programmes CGI, d'autres directives RewriteRule, ou des +directives CustomLog.
+ +L'exemple suivant définit une variable d'environnement nommée 'image' +avec une valeur de '1' si l'URI de la requête correspond à un fichier +image. Cette variable d'environnement est ensuite utilisée pour exclure +une telle requête du journal des accès.
+ +Notez que le même effet peut être obtenu à l'aide de la directive
+
L'utilisation du drapeau [F] permet de faire envoyer par le serveur au
+client un code de statut "403 Forbidden". Le même effet peut être obtenu à
+l'aide de la directive
La règle suivante va interdire la téléchargement de fichiers
+.exe depuis votre serveur.
Cet exemple utilise la syntaxe "-" pour la cible de réécriture, ce +qui signifie que l'URI de la requête n'est pas modifié. Il n'y a aucune +raison de réécrire un URI, si vous avez l'intention d'interdire la +requête.
+ +Lorsqu'on utilise [F], [L] est implicite - c'est à dire que la +réponse est renvoyée immédiatement, et aucune autre règle n'est évaluée.
+ +Le drapeau [G] permet de faire envoyer par le serveur un code de statut +"410 Gone" avec la réponse. Ce code indique qu'une ressource qui était +disponible auparavant ne l'est plus actuellement.
+ +Comme dans le cas du drapeau [F], on utilise en général la syntaxe +"-" pour la cible de réécriture lorsqu'on utilise le drapeau [G] :
+ +Lorsqu'on utilise [F], [L] est implicite - c'est à dire que la +réponse est renvoyée immédiatement, et aucune autre règle n'est évaluée.
+ +Force le traitement de la requête résultante par le gestionnaire +spécifié. Par exemple, on peut utiliser ce drapeau pour forcer +l'interprétation de tous les fichiers sans extension par le gestionnaire +php :
+ +
+L'expression rationnelle ci-dessus - !\. - correspond à
+toute requête qui ne contient pas le caractère ..
+
On peut aussi utiliser ce drapeau pour forcer l'utilisation d'un
+certain gestionnaire en fonction de certaines conditions. Par exemple,
+l'extrait suivant utilisé dans un contexte de niveau serveur permet de
+faire en sorte que les fichiers .php soient
+affichés par mod_php dans le cas où ils font
+l'objet d'une requête avec l'extension .phps :
L'expression rationnelle ci-dessus -
+^(/source/.+\.php)s$ - va correspondre à toute requête qui
+débutera par /source/, continuera par 1 ou n caractères
+puis par .phps. La référence arrière $1 fait référence à la
+correspondance capturée entre parenthèses de l'expression
+rationnelle.
Lorsque le drapeau [L] est présent, last, ou
+à la commande break en C. Utilisez ce drapeau pour indiquer
+que la règle courante doit être appliquée immédiatement, sans tenir
+compte des règles ultérieures.
Si vous utilisez des règles .htaccess ou des sections .htaccess ou la section
Si vous utilisez des directives
Un autre drapeau, [END], permet non seulement d'interrompre le cycle +courant du processus de réécriture, mais aussi d'empêcher toute +réécriture ultérieure dans le contexte de répertoire (htaccess). Ceci ne +s'applique pas aux nouvelles requêtes résultant de redirections +externes.
+ +Dans l'exemple donné ici, toute requête est réécrite en
+index.php, la requête originale étant ajoutée comme chaîne
+de requête en argument à index.php ; cependant, la
+directive index.php, la directive
Le drapeau [N] provoque un redémarrage du traitement des règles +depuis le début, en utilisant le résultat du jeu de règles, sous +réserve qu'il existe un point de démarrage ; à utiliser avec précautions +car il peut provoquer un bouclage infini. +
++Le drapeau [Next] peut servir, par exemple, +à remplacer de manière répétitive +une chaîne de caractère ou une lettre dans une requête. Dans l'exemple +suivant, chaque occurence de A sera remplacée par B dans la requête, et +ceci jusqu'il n'y ait plus de A à remplacer. +
+ +Vous pouvez vous représenter ce traitement comme une boucle
+while : tant que le modèle de la règle correspond (c'est à
+dire, tant que l'URI contient un A),
+effectuer la substitution (c'est à dire, remplacer le A par
+un B).
Avec le drapeau [NC], le modèle de la règle
Dans l'exemple suivant, toute requête pour un fichier image sera
+transmise par Apache à votre serveur d'images dédié. La correspondance est
+insensible à la casse, si bien que par exemple, .jpg aussi
+bien que .JPG seront acceptés.
Par défaut, les caractères spéciaux, comme & et
+?, sont convertis en leur équivalent
+hexadécimal. Le drapeau [NE] permet d'éviter cette conversion.
+
+Dans l'exemple ci-dessus, /anchor/xyz est réécrit en
+/bigpage.html#xyz. En l'absence du drapeau [NE], le #
+aurait été converti en son équivalent hexadécimal, %23, ce
+qui aurait provoqué un code d'erreur "404 Not Found".
+
Le drapeau [NS] empêche la règle de s'appliquer aux sous-requêtes.
+Par exemple, une page incluse au moyen d'une SSI (Server
+Side Include) est une sous-requête, et vous ne voudrez probablement pas que
+la réécriture s'applique à ces sous-requêtes. Ainsi, lorsque
+index.html), il s'agit d'une sous-requête interne, et vous
+ne désirez en général pas que ces sous-requêtes soient réécrites. Cette
+réécriture
+n'est pas toujours utile pour les sous-requêtes, et peut même causer des
+erreurs si l'ensemble du jeu de règles est appliqué. L'utilisation de
+ce drapeau permet d'exclure les règles qui peuvent poser problème.
Comment déterminer si vous devez utiliser cette règle ou non : si +vous préfixez les URLs avec des scripts CGI, afin de forcer leur +traitement par le script CGI, vous vous exposez à des problèmes (ou du +moins à une surcharge significative) avec les sous-requêtes. Dans ces +cas, vous devez utiliser ce drapeau.
+ ++Les images, scripts java, ou fichiers css, chargés en tant que partie +d'une page html, ne sont pas des sous-requêtes - le navigateur les +appelle sous forme de requêtes HTTP à part entière. +
+L'utilisation du drapeau [P] entraîne le traitement de la requête par
+le module
L'utilisation du drapeau [P] provoque aussi l'effet du drapeau [L] - +autrement dit, la requête est immédiatement envoyée au mandataire, et +toute règle ultérieure sera ignorée.
+ +
+Vous devez vous assurer que la chaîne de substitution soit un URI valide
+(commençant typiquement par http://nom-serveur)
+qui puisse être traitée par le module
Note:
+Par défaut, la cible (ou chaîne de substitution) d'une règle
+RewriteRule est sensée être un chemin de fichier. Avec le drapeau [PT],
+par contre, elle est traitée comme un URI. Autrement dit, avec le
+drapeau [PT], le résultat de la règle
+Si par exemple, vous avez un
+Dans l'exemple précédent, en l'absence du drapeau [PT], l'Alias aurait +été ignoré, ce qui aurait provoqué une erreur 'File not found'. +
+ +Avec le drapeau PT, le drapeau L est
+implicite : la réécriture s'arrêtera afin de transmettre la requête à la
+phase suivante du traitement.
Notez que le drapeau PT est implicite dans des contextes
+de répertoire comme les sections .htaccess. Le seul moyen de contourner ceci consiste à
+réécrire vers -.
+Quand l'URI de remplacement contient une chaîne de requête, le
+comportement par défaut de la règle
+query string (il s'agit des paramètres éventuellement passés dans l'URL après le
+caractère ?, usuellement pour les formulaires traités par la
+méthode HTTP GET) existante, et de la remplacer par celle nouvellement créée.
+Avec le drapeau [QSA], les chaînes de requête peuvent être combinées.
+
Considérons la règle suivante :
+ +Avec le drapeau [QSA], une requête pour
+/pages/123?one=two sera réécrite en
+/page.php?page=123&one=two. Sans le drapeau [QSA], la
+même requête sera réécrite en /page.php?page=123 -
+autrement dit, la chaîne de requête (query string) existante sera supprimée.
+
+Lorsque l'URI de la requête contient une chaîne de paramètres, et si
+l'URI cible n'en contient pas, le comportement par défaut de la
+directive
Ce drapeau est disponible dans les versions 2.4.0 et supérieures.
+ ++Lorsque les drapeaux [QSD] et [QSA] sont utilisés ensemble, c'est le +drapeau [QSD] qui l'emporte. +
+ ++Si l'URI cible possède une chaîne de paramètres, le comportement par +défaut sera respecté - c'est à dire que la chaîne de paramètres +originale sera supprimée et remplacée par la chaîne de paramètres de +l'URI cible. +
+ +
+L'utilisation du drapeau [R] provoque l'envoi d'une redirection au
+navigateur. Si une URL pleinement qualifiée (FQDN - fully qualified domain name)
+ est spécifiée (c'est à dire incluant http://nom-du-serveur/),
+ une redirection sera effectuée vers cette adresse. Dans le cas contraire,
+ le protocole courant, le nom du serveur et le numéro de port seront
+ utilisés pour générer l'URL envoyée avec la redirection.
+
Tout code de statut de réponse HTTP valide peut être +spécifié, en utilisant la syntaxe [R=305], le code de statut 302 étant +utilisé par défaut si aucun code n'est spécifié. Le code de statut +spécifié n'est pas nécessairement un code de statut de redirection (3xx). +
+ +Si le code de statut est en dehors de la plage des codes de
+redirection (300-399), la chaîne de substitution est entièrement
+supprimée, et la réécriture s'arrête comme si le drapeau L
+était utilisé.
En plus des codes de statut de réponse, vous pouvez spécifier les
+codes de redirection en utilisant leurs noms symboliques :
+temp (défaut), permanent, ou
+seeother.
+Vous utiliserez presque toujours [R] en conjonction avec [L] (c'est à
+dire [R,L]), car employé seul, le drapeau [R] préfixe l'URI avec
+http://cet-hôte[:ce-port], mais passe ensuite cette adresse
+à la règle suivante, ce qui provoquera le plus souvent des
+avertissements 'Invalid URI in request'.
+
Le drapeau [S] sert à sauter des règles que vous ne voulez pas voir
+exécuter. Ceci peut s'interpréter comme une instruction
+goto dans votre jeu de règles de réécriture. Dans
+l'exemple suivant, nous ne voulons exécuter la règle
Cette technique trouve son utilité dans le fait qu'une directive
+RewriteCond s'applique à plusieurs règles
+RewriteRule, une technique possible consiste à inverser ces
+conditions et à utiliser le drapeau [Skip]. Cette technique permet
+d'élaborer des pseudo-constructions if-then-else : la dernière règle du
+bloc then contiendra skip=N, où N est le nombre de règles
+contenues dans le bloc else.
Définit le type MIME de la réponse résultante renvoyée. L'effet est
+identique à celui de la directive
Par exemple, vous pouvez utiliser la technique suivante pour servir +du code source Perl en tant que plein texte, s'il est requis d'une +certaine manière :
+ +Ou encore, si vous possédez une caméra qui produit des fichiers +images jpeg sans extension, vous pouvez forcer le renvoi de ces images +avec le type MIME correct en se basant sur le nom du fichier :
+ +Notez cependant qu'il s'agit d'un exemple trivial, et que le problème
+aurait pu être résolu en utilisant à la place la directive
+Dans un contexte de niveau répertoire, n'utilisez que -
+(tiret) comme substitution, dans toute la séquence de réécriture de
+mod_rewrite, sinon le type MIME défini avec ce drapeau
+sera perdu suite à un retraitement interne (y compris les séquences de
+réécriture suivantes de mod_rewrite). Dans ce contexte, vous pouvez
+utiliser le drapeau L pour terminer la séquence
+courante de réécriture de mod_rewrite.
Apache HTTP Server Version 2.2
+
Available Languages: en
+This document supplements the mod_rewrite
+reference documentation. It describes
+the way that the rules change when you use mod_rewrite in .htaccess files,
+and how to deal with these changes.
Available Languages: en
+This document supplements the
-- -``The great thing about mod_rewrite is it gives you - all the configurability and flexibility of Sendmail. - The downside to mod_rewrite is that it gives you all - the configurability and flexibility of Sendmail.''
--- Brian Behlendorf
+
- Apache Group-
mod_rewriteprovides a way to modify incoming + URL requests, dynamically, based on regular + expression rules. This allows you to map arbitrary URLs onto + your internal URL structure in any way you like.
-- -``Despite the tons of examples and docs, - mod_rewrite is voodoo. Damned cool voodoo, but still - voodoo.''
- --- Brian Moore
- -
- bem@news.cmc.net
Welcome to mod_rewrite, the Swiss Army Knife of URL - manipulation!
- -This module uses a rule-based rewriting engine (based on a - regular-expression parser) to rewrite requested URLs on the - fly. It supports an unlimited number of rules and an +
It supports an unlimited number of rules and an unlimited number of attached rule conditions for each rule to provide a really flexible and powerful URL manipulation - mechanism. The URL manipulations can depend on various tests, - for instance server variables, environment variables, HTTP - headers, time stamps and even external database lookups in - various formats can be used to achieve granular URL + mechanism. The URL manipulations can depend on various tests: + server variables, environment variables, HTTP + headers, time stamps, external database lookups, and various other + external programs or handlers, can be used to achieve granular URL matching.
-This module operates on the full URLs (including the
- path-info part) both in per-server context
- (httpd.conf) and per-directory context
- (.htaccess files and <Directory>
- blocks) and can even generate query-string
- parts on result. The rewritten result can lead to internal
- sub-processing, external request redirection or even to an
- internal proxy throughput.
Rewrite rules can operate on the full URLs, including the path-info
+ and query string portions, and may be used in per-server context
+ (httpd.conf), per-virtualhost context (<VirtualHost> blocks), or
+ per-directory context (.htaccess files and <Directory> blocks). The
+ rewritten result can lead to further rules, internal
+ sub-processing, external request redirection, or proxy
+ passthrough, depending on what flags you
+ attach to the rules.
Since mod_rewrite is so powerful, it can indeed be rather + complex. This document supplements the reference documentation, and + attempts to allay some of that complexity, and provide highly + annoted examples of common scenarios that you may handle with + mod_rewrite. But we also attempt to show you when you should not + use mod_rewrite, and use other standard Apache features instead, + thus avoiding this unnecessary complexity.
-But all this functionality and flexibility has its - drawback: complexity. So don't expect to understand this - entire module in just one day.
-``mod_rewriteâı harika yapan Åey, Sendmailâın tüm yapılandırma @@ -74,9 +76,9 @@
Belgeler
-+``mod_rewrite ææ£çä¸ç¹æ¯å®ä¸º Sendmail - æä¾äºææçå¯é ç½®æ§åçµæ´»æ§ãmod_rewrite - ç缺ç¹ä¹æ¯å®ä¸º Sendmail æä¾äºææçå¯é ç½®æ§åçµæ´»æ§ã''
+-
mod_rewriteæä¾äºåºäºæ£å表达å¼è§åå¨æä¿®æ¹ä¼ å ¥ç请æ±ç URL çæ¹æ³ã + è¿å è®¸ä½ ä»¥èªå·±å欢çä»»ææ¹æ³æ å°ä»»æ URL å°ä½ çå é¨ URL ç»æã-- Brian Behlendorf
+
- Apache Group宿¯ææ éçè§åï¼ä»¥å为æ¯ä¸ªè§åéå æ¡ä»¶ï¼ä»èæä¾äºä¸ä¸ªçæ£çµæ´»ä¸å¼ºå¤§ç URL + æä½æºå¶ãURL æä½å¯ä»¥ä¾èµäºåç§æµè¯ï¼ä¾å¦æå¡å¨åéï¼ç¯å¢åéï¼HTTP + å¤´ï¼æ¶æ³ï¼çè³å¤é¨æ°æ®åºæ¥è¯¢çï¼ä»¥ä¾¿å®æ URL åå å¹é ã
-
è¿ä¸ªæ¨¡å卿å¡å¨ä¸ä¸æ (httpd.conf)ï¼èæä¸»æºä¸ä¸æ (<VirtualHost> æä»¤å)ï¼ç®å½ä¸ä¸æ
+ (.htaccess æä»¶å <Directory>
+ æä»¤å) 坹宿´ç URL (å
å«ç®å½ä¿¡æ¯é¨ååæ¥è¯¢å符串é¨å) æä½ã
+ éåç»æå¯ä»¥å¯¼è´æ°çè§åå¤çï¼å
é¨çåç»å¤çï¼å¤é¨è¯·æ±éå®åï¼çè³éè¿å
é¨ä»£çï¼
+ è¿åå³äºä½ 为è§åéå çæ å¿ã
-- -``尽管æé常å¤çä¾ååææ¡£ï¼ mod_rewrite 便§æ¯éæ¯ã - 该æ»ç鿝ï¼ç»å¦ç鿝ï¼è¿æ¯éæ¯ã''
+æ¢ç¶ mod_rewrite è¿ä¹å¼ºå¤§ï¼å®å½ç¶æ¯ç¸å½å¤æãè¿ç¯ææ¡£ä½ä¸ºåèæåçè¡¥å ï¼è¯å¾åè½»ä¸äºå¤ææ§ï¼ + æä¾ä½ å¯è½ä½¿ç¨ mod_rewrite ç常è§åºæ¯çæå åæ³¨éçä¾åã + 使¯ï¼æä»¬ä¹è¯å¾åè¯ä½ ï¼å¨ä»ä¹æ¶åä½ ä¸åºå½ä½¿ç¨ mod_rewriteï¼ + å¯ä»¥ä½¿ç¨å ¶å®æ åç Apache ç¹æ§æ¥è¾¾å°ç®çï¼ä»¥é¿å æ è°ç夿æ§ã
--- Brian Moore
- -
- bem@news.cmc.net
欢è¿ä½¿ç¨ mod_rewriteï¼æä½ URL çç士åå!
- -è¿ä¸ªæ¨¡åå¨å¤çè¯·æ±æ¶ï¼ä½¿ç¨åºäºè§åçéå弿 - (åºäºæ£å表达å¼è§£æå¨) æ¹å请æ±ç URLã - 宿¯ææ éçè§åï¼ä»¥å为æ¯ä¸ªè§åéå æ¡ä»¶ï¼ä»èæä¾äºä¸ä¸ªçæ£çµæ´»ä¸å¼ºå¤§ç URL - æä½æºå¶ãURL æä½å¯ä»¥ä¾èµäºåç§æµè¯ï¼ä¾å¦æå¡å¨åéï¼ç¯å¢åéï¼HTTP - å¤´ï¼æ¶æ³ï¼çè³å¤é¨æ°æ®åºæ¥è¯¢çï¼ä»¥ä¾¿å®æ URL åå å¹é ã
- -è¿ä¸ªæ¨¡å卿å¡å¨ä¸ä¸æ (httpd.conf)ï¼ç®å½ä¸ä¸æ
- (.htaccess æä»¶å <Directory>
- æä»¤å) 坹宿´ç URL (å
å«ç®å½ä¿¡æ¯é¨å) æä½ï¼çè³å¯ä»¥å¨ç»æä¸äº§çæ¥è¯¢å符串é¨åã
- éåç»æå¯ä»¥å¯¼è´å
é¨çåç»å¤çï¼å¤é¨è¯·æ±éå®åï¼çè³éè¿å
é¨ä»£çã
使¯ææè¿äºåè½åçµæ´»æ§é½æå ¶ç¼ºç¹: 夿æ§ãå æ¤ï¼ä½ ä¸è¦ææè½å¨ä¸å¤©å çè§£è¿æ´ä¸ªæ¨¡åã
- -