Question

With my apache 2.4 I want the following:

  • GET /file.html -> 301 redirect to path /~
  • GET /~ -> return content of file /file.html

In my .htaccess I have the following:

RewriteEngine on
RewriteBase /

RewriteRule ^file.html ~ [R=301,L]
RewriteRule ^~ file.html [L]

But now also GET /~ returns a 301 redirect to /~. Where is the bug? I thought, that for GET /~ the first rule is not applied and the second rule will return the content of file file.html. Is this what I want possible with mod_rewrite?

Was it helpful?

Solution

Problem with your rules is that it will cause infinite looping since both rules are rewriting like this: A->B and B->A.

You can use this rule to avoid looping:

RewriteEngine on
RewriteBase /

RewriteCond %{THE_REQUEST} \s/+file\.html\s [NC]
RewriteRule ^ ~ [R=302,L,NE]

RewriteRule ^~$ file.html [L,B]

THE_REQUEST variable represents original request received by Apache from your browser and it doesn't get overwritten after execution of some rewrite rules.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top